Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
2  
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. –  Markus von Broady Oct 16 '12 at 13:26
add comment

1 Answer 1

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

screenScale=canvasWidth/box2DWidth;

pos=this.physBody.GetPosition();

canvasContext.drawImage(images.spriteSheet,
            226, 871, //sourceImgX, sourceImgY
            100, 80,  // sourceImgWidth, sourceImgHeight
            pos.x*screenScale,
            (pos.y-this.princeData.height)*screenScale, // canvasX, canvas Y           
            this.princeData.width*screenScale,
            this.princeData.height*screenScale); // width, height
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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