HTML and CSS Reference
In-Depth Information
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:
iif ( ball . y + ball . radius <= theCanvas . height ) {
ball . velocityy += gravity ;
} else
else {
ball . velocityx = 0 ;
ball . velocityy = 0 ;
ball . y = theCanvas . height - ball . radius ;
}
With this:
ball . velocityy += gravity ;
iif (( 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
vectorandgravityisappliedeverytime drawScreen() iscalled,theballwilleventuallycome
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.
Search WWH ::




Custom Search