Units in Box2dWeb
The first Box2D objects we will create are the four walls that define the area that holds our balls (a 500×400 Canvas). These walls are similar to the boundaries we defined in code for the earlier bouncing balls demos. We will define the walls as dynamic objects in an array, each with four properties:
{
x
:
,
x
position
,
y
:
y
position
,
w
:
width
,
h
:
height
}
var
wallDefs
=
new
Array
(
{
x
:
8.3
,
y
:
.
03
,
w
:
8.3
,
h
:
.
03
},
//top wall
{
x
:
8.3
,
y
:
13.33
,
w
:
8.3
,
h
:
.
03
},
//bottom wall
{
x
:
0
,
y
:
6.67
,
w
:
.
03
,
h
:
6.67
},
//left wall
{
x
:
16.7
,
y
:
6.67
,
w
:
.
03
,
h
:
6.67
}
);
//right wall
Notice that the values defined above do not look like anything we have used before. The values are in MTS units. As we stated earlier, MTS units refer to “meters-tonne-second” and are used represent large objects and spaces. However, because we draw everything in pixels on the Canvas, we need a way to think of MTS units in terms of the Canvas and vice versa.
To get these values, we need to choose a “scale” value to scale
the Canvas pixels to MTS units. For this example (and all the examples
in the rest of this chapter), we have chosen the value 30
as the scale value to translate pixels to
MTS units.
At the same time, objects displayed in Box2D have their origin at the center (not the upper-left corner), so we need to compensate for that as well. Figure 5-25 shows how the units translate and the relative origins of the walls.
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.