HTML and CSS Reference
In-Depth Information
</script>
</body>
</html>
You can see the results of this example in Figure 14-5. Of couse, the segment chain doesn't have to chase
the mouse all day. Let's see what happens when we give it a toy to play with.
Figure 14-5. Multiple-segment reaching
Reaching for an Object
Again, we build off the previous example. This time we need the Ball class, so include that file in your
document. Then create some new variables at the top of the script for the ball to use as it moves around:
var ball = new Ball(20),
gravity = 0.5,
bounce = -0.9;
ball.vx = 10; //start the ball with velocity on the x axis
We're also going to shrink the segments down a little bit, to give them more room to play. You can adjust
these values to see what looks best in your animation:
while (numSegments--) {
segments.push( new Segment(20, 10) );
}
Create another function, moveBall , that allows us to separate the ball-moving code so it doesn't clutter up
the program:
function moveBall () {
ball.vy += gravity;
ball.x += ball.vx;
ball.y += ball.vy;
if (ball.x + ball.radius > canvas.width) {
ball.x = canvas.width - ball.radius;
ball.vx *= bounce;
} else if (ball.x - ball.radius < 0) {
 
Search WWH ::




Custom Search