Simple Gravity with a Bounce

The last example showed what a cannonball might look like if it were shot out, landed on a surface, and stuck there with no reaction. However, even a heavy cannonball will bounce when it hits the ground.

To create a bouncing effect, we do not have to change the code very much at all. In drawScreen(), we first apply gravity on every frame; then, instead of stopping the ball if it hits the bottom of the canvas, we simply need to reverse the y velocity of ball when it hits the ground.

In CH5EX14.html you would replace this code:

if (ball.y + ball.radius <= theCanvas.height) {
   ball.velocityy += gravity;
} else {
   ball.velocityx = 0;
   ball.velocityy = 0;
   ball.y = theCanvas.height - ball.radius;
}

With this:

ball.velocityy += gravity;
if ((ball.y + ball.radius) > theCanvas.height) {
   ball.velocityy = -(ball.velocityy)
}

This code will send the ball bouncing back “up” the canvas. Because it is still traveling on the vector and gravity is applied every time drawScreen() is called, the ball will eventually come down again as the applied gravity overtakes the reversed y velocity.

Figure 5-19 shows what the cannonball looks like when the bounce is applied.

A ball moving on a vector with gravity and a bounce applied

Figure 5-19. A ball moving on a vector with gravity and a bounce applied

Note

To achieve a nice-looking bounce for this example, we also changed the angle of the vector in canvasApp() to 295:

var angle = 295;

Example 5-15 offers ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.