HTML and CSS Reference
In-Depth Information
var dx = ball.x - centerBall.x,
dy = ball.y - centerBall.y,
dist = Math.sqrt(dx * dx + dy * dy),
min_dist = ball.radius + centerBall.radius;
if (dist < min_dist) {
var angle = Math.atan2(dy, dx),
tx = centerBall.x + Math.cos(angle) * min_dist,
ty = centerBall.y + Math.sin(angle) * min_dist;
ball.vx += (tx - ball.x) * spring;
ball.vy += (ty - ball.y) * spring;
}
ball.draw(context);
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(move);
balls.forEach(draw);
centerBall.draw(context);
}());
};
</script>
</body>
</html>
This is a lot of code, but you've already seen most of these techniques in earlier chapters. Let's walk
through it quickly.
Starting at the top of the script, you create the centerBall and then loop through and create the smaller,
moving, balls. They are given a random size, position, color, and velocity.
Within the drawFrame animation loop, we iterate over the balls twice. To separate functionality, the motion
code has been placed in a function called move . This takes a reference to one of the balls and applies all
the basic motion code to it—it's basic velocity code with bouncing. Then, in the draw function, you find the
distance from a given ball to the centerBall , and compute the minimum distance to determine a collision.
If there is a collision, you find the angle between the two, and use that plus the minimum distance to
calculate a target x and y. This target will be right on the outer edge of the centerBall .
From there, you just apply basic spring code to spring to that point (as described in Chapter 8). Of course,
once it reaches that point, it's no longer colliding and will fly off in whatever direction it's heading. We then
draw the balls to the canvas.
See how you can build up and layer simple techniques to wind up with some very complex motion?
Multiple-object collision detection strategies
When you have just a couple of objects moving around the screen, it's pretty simple to test them against
each other. But when you get several objects, or even dozens, you need some kind of strategy for how to
 
Search WWH ::




Custom Search