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?

  • 2
    \$\begingroup\$ You need to scale your view into current canvas size. Simply take current_width and divide it by designed_width and get the scale. Then you multiply all coordinates by the scale. If you designed your game for 500 pixels width, a user has his canvas of 1000 pixels width, scale = current_width/designed_width = 2. If you want to draw a vertical line in middle: x: 250, then multiply it by scale x *= 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. \$\endgroup\$ Oct 16 '12 at 13:26

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.

pos is the position of character body in the box2d world .

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).



            226, 871, //sourceImgX, sourceImgY
            100, 80,  // sourceImgWidth, sourceImgHeight
            (pos.y-this.princeData.height)*screenScale, // canvasX, canvas Y           
            this.princeData.height*screenScale); // width, height

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.