I'm new with HTML5 canvas and Box2DWeb and I'm trying to make an Asteroids game. So far I think I'm doing okay, but one thing I'm struggling to comprehend is how positioning works in relation to the canvas. I understand that Box2DWeb is only made to deal with physical simulation, but I don't know how to deal with positioning on the canvas. The canvas is 100% viewport and thus can vary size. I want to fill the screen with some asteroids, but if I hardcore certain values such as bodyDef.position.x = Math.random() * 50; the asteroid may appear off canvas for someone with a smaller screen? Can anybody help me understand how I can deal with relative positioning on the canvas?
To expand on Markus's comment, here is some code from my game. In this code, princeData.width & princeData.height are the width& height of my character in BOX2D.
I keep all dimensions (sizes and positions) in the game as coordinates in the Box2d world, I only need to convert when drawing. The on-screen size & position will need to change as the browser window gets bigger or smaller. I have some other code which keeps the aspect ratio of the canvas constant, so I only need to worry about one scaling factor (screenScale).
|
||||
|
scale = current_width/designed_width
= 2. If you want to draw a vertical line in middle: x: 250, then multiply it by scalex *= scale
==>x = x * 2
= 500, and therefore it will still be in middle of the canvas as 500 is in middle betweeon 0 and 1000. – Markus von Broady Oct 16 '12 at 13:26