HTML and CSS Reference
In-Depth Information
Now that we have that out of the way, let's start by making our lives a lot easier. Instead of
using a literal for our scale factor, we will create a variable named
scaleFactor
that we can
use for scale conversions:
var
var
scaleFactor
=
30
;
We can use
scaleFactor
when finding positions and sizes for our objects in Box2D. First, in
theloopwherewecreated theballstodisplay,wenowusetheentire canvaswidthandheight,
modified by the
scaleFactor
to randomly position the balls:
var
var
ypos
=
(
Math
.
random
()
*
theCanvas
.
height
)
/
scaleFactor
;
var
var
xpos
=
(
Math
.
random
()
*
theCanvas
.
width
/
scaleFactor
);
var
var
size
=
((
Math
.
random
()
*
20
)
+
5
)
/
scaleFactor
;
We also now define the
wallDefs
using the width and height of the Canvas instead of the
MTS values we used in the previous examples. This is essentially the same, but it makes it
much easier to adjust the size of the Canvas now that we are not using literals. Because our
Canvas is now smaller, it helps that we don't have to recalculate all the values:
var
var
wallDefs
=
new
new
Array
(
{
x
:
theCanvas
.
width
,
y
:
0
,
w
:
theCanvas
.
width
,
h
:
1
},
//top
{
x
:
theCanvas
.
width
,
y
:
theCanvas
.
height
,
w
:
theCanvas
.
width
,
h
:
1
},
//bottom
{
x
:
0
,
y
:
theCanvas
.
height
,
w
:
1
,
h
:
theCanvas
.
height
},
//left
{
x
:
theCanvas
.
width
,
y
:
theCanvas
.
height
,
w
:
1
,
h
:
theCanvas
.
height
} );
//right
In the loop where we define the walls, we now use
scaleFactor
to convert the pixels values
in our array to MTS values for positions and sizes of the walls:
wallDef
.
position
.
Set
(
wallDefs
[
i
].
x
/
scaleFactor
,
wallDefs
[
i
].
y
/
scaleFactor
);
...
wallFixture
.
shape
.
SetAsBox
(
wallDefs
[
i
].
w
/
scaleFactor
,
wallDefs
[
i
].
h
/
scaleFactor
);
When we define our instance of
b2DebugDraw
, we pass a reference to the second Canvas
(
context2
) so that the debug output will display there, and we can draw on the first Canvas
with the Canvas drawing API:
debugDraw
.
SetSprite
(
context2
);
debugDraw
.
SetDrawScale
(
scaleFactor
);
//define scale
The big changes for this example arrive in
drawScreen()
. The calls to the methods of the
world object are the same as in the last example (even though
world.DrawDebugData()
is
now using
context2
):
function
function
drawScreen
() {
world
.
Step
(
1
/
60
,
10
,
10
);