HTML and CSS Reference
In-Depth Information
var ballA = new Ball(Math.random() * 100),
ballB = new Ball(Math.random() * 100);
This way, they will be different sized each time the code is run, and yet the collision detection always
works perfectly.
Collision-based springing
The problem with giving you a good working example of distance-based hit testing is that a complete
program would involve a lot of issues related to things that haven't been covered yet, such as the reaction
of two objects when they hit, and how to efficiently handle interactions between many objects. But we'll
create an example that demonstrates hit testing without too much code that you haven't already seen.
The basic idea is to place one large ball, called centerBall , in the center of the canvas. Then add in a
bunch of smaller balls, giving them random sizes and velocities. These will move with basic motion code
and bounce off the walls. On each frame, perform a distance-based collision check between each moving
ball and the center ball. If you detect a collision, calculate an offset spring target based on the angle
between the two balls and the minimum distance to avoid collision. All it really means is that if a moving
ball collides with the center ball, you make it spring back out again. You do this by setting a target just
outside the center ball, and the moving ball springs to that target. Then, once it reaches the target, it is no
longer colliding, so the spring action ends, and it just moves with its regular motion code.
The result is kind of like bubbles bouncing off a large bubble, as shown in Figure 9-9. The little bubbles
enter into the big one a bit, depending on how fast they are going, but then spring back out.
Figure 9-9. Collision-based springing
Here is the code for the example (document 06-bubbles-1.html ):
 
Search WWH ::




Custom Search