HTML5 Canvas [87]
ball.y += ball.velocityy;
ball.x += ball.velocityx;
context.fillStyle = "#000000";
context.beginPath();
context.arc(ball.x,ball.y,ball.radius,0,Math.PI*2,true);
context.closePath();
context.fill();
Figure 5-17 shows what the path looks like when simple gravity is applied to a ball moving on a vector. We have added the points to illustrate the path.
Figure 5-17. Simple gravity with an object moving on a vector
You can test out Example 5-14 with the file CH5EX14.html in the code distribution, or type in the full code listing below.
Example 5-14. Simple gravity
a
Simple Gravity with a Bounce
The last example showed what a cannonball might look like if it was 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. Since 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-18 shows what the cannonball looks like when the bounce is applied.
Figure 5-18. 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 the full code.
Example 5-15. Simple gravity with a bounce
-->