HTML and CSS Reference
In-Depth Information
ball.x = ball.radius;
ball.vx *= bounce;
}
if (ball.y + ball.radius > canvas.height) {
ball.y = canvas.height - ball.radius;
ball.vy *= bounce;
} else if (ball.y - ball.radius < 0) {
ball.y = ball.radius;
ball.vy *= bounce;
}
}
Finally, in the drawFrame animation loop, call the moveBall function, and have the first segment reach for
the ball instead of the mouse:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
moveBall();
target = reach(segments[0], ball.x, ball.y );
segments.forEach(move);
segments.forEach(draw);
ball.draw(context);
}());
When you run this example you should see something like Figure 14-6. The ball now bounces around, and
the arm follows it. Pretty amazing, right?
Figure 14-6. It likes to play ball.
Right now, the arm touches the ball, but the ball completely ignores the arm. Let's have them interact.
Adding Some Interaction
How the ball and the arm interact depends on what you want them to do. But, no matter what you do, the
first thing you need is some collision detection. Then, you can have the reaction if there is a collision.
Again, put all the code into its own function and call it from the drawFrame animation loop:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
 
Search WWH ::




Custom Search