Quantcast
Channel: Gaming Think Tank » Box2D
Viewing all articles
Browse latest Browse all 2

Box2d coordinate system for HTML5 Canvas

0
0

Original coordinate system of Box2d is old fashioned Cartesian coordinate system having its origin at its center. Box2d follows the rules of Physics and it knows nothing about HTML5 canvas  or any other platform. But, its drawing method(s) recognizes and respects the coordinate system if you are developing games for HTML5 canvas platform with Box2dWeb library. Probably it also behaves in similar manner for other platforms like iOS and Flash, but I am not sure as I haven’t tried Box2d on them yet.

Box2D cartesian coordinate system

Box2D Cartesian coordinate system

HTML5 canvas has its origin at top left corner. x-axis increases to the right and y-axis increases downwards.

html5 coordinate system

HTML5 coordinate system

There are a couple of more important concepts that you need to understand to draw shapes, on HTML5 canvas using Box2D,  exactly where you want to see them and with desired dimensions. Let’s say, you want to draw a rectangle on the canvas. Width and height of the rectangle is 4 meters (Box2D talks in meters, not in pixels). Box2D wants you to provide half of the required dimensions.

box2d rectangle dimensions

Box2D rectangle dimensions


var width = 2;
var height = 2;
fixDef.shape.SetAsBox(width, height); //Half of the actual width and height

Now you want to place this rectangle somewhere on the canvas, say…at top let corner. Here you need to understand a very important concept…Box2D wants you to tell him where you want to place the center of the rectangle. So, if you place the center of the rectangle at x=0,y=0 you would see only half of the actual rectangle. To view the rectangle properly, you would add width and height of the rectangle to the desired coordinates. And again, the width and height is half of the actual width and height in meters.


var x = 0;
var y = 0;
bodyDef.position.Set( x + width, y + height);

At this point of time, you know exactly how coordinate system works. You also know how to set dimensions of an object and how to place that object on the canvas.

The more I think, the more confused I get.

The more I think, the more confused I get.

LOL…Stop thinking and start doing. There is an exercise for now. Try to place the rectangle at the bottom of the canvas covering width of the canvas and one fourth of the height of the canvas.

Here is the code for you to play with.

The post Box2d coordinate system for HTML5 Canvas appeared first on Gaming Think Tank.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images