HTML and CSS Reference
In-Depth Information
of control.) We then compare that distance value to the sum of the radius of each ball.
If the distance is less than or equal to the sum of the radii, we have a collision. This is
a very simple and efficient way to test collisions, and it works especially well with
collisions among balls in 2D:
function hitTestCircle(ball1,ball2) {
var retval = false;
var dx = ball1.nextx - ball2.nextx;
var dy = ball1.nexty - ball2.nexty;
var distance = (dx * dx + dy * dy);
retval = true;
}
return retval;
}
Figure 5-9 illustrates this code.
Figure 5-9. Balls colliding
Separating the code in drawScreen()
The next thing we want to do is simplify drawScreen() by separating the code into
controllable functions. The idea here is that to test collisions correctly, we need to make
sure some of our calculations are done in a particular order. We like to call this an
update-collide-render cycle .
update()
Sets the nextx and nexty properties of all the balls in the balls array.
testWalls()
Tests to see whether the balls have hit one of the walls.
collide()
Tests collisions among balls. If the balls collide, updates nextx and nexty .
Search WWH ::

Custom Search