HTML and CSS Reference
In-Depth Information
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="500" height="500">
Your browser does not support HTML5 Canvas.
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 even-
tually 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.
Search WWH ::

Custom Search