Online Book Reader

Home Category

HTML5 Canvas [89]

By Root 6593 0

With gravity applied, the bounce is not exactly as you might expect. Gravity is always pulling down on our object, so the effect of a loss of y velocity due to an elastic bounce is pronounced.

The full code is shown in Example 5-16.

Example 5-16. Simple gravity with bounce and elasticity

CH5EX16: Gravity With A Vector With Bounce And Elasticity

Your browser does not support HTML5 Canvas.

Simple Gravity, Simple Elasticity, and Simple Friction


Now that we have a ball traveling on a vector that is affected by both gravity and elasticity, we have one more element to add to make the animation more realistic. In the previous example, the y velocity was affected by gravity and elasticity, but the ball still traveled on the x-axis without any degradation in velocity. We will fix this issue now by adding friction into the equation.

In physics, friction is a force that resists the motion of an object. We have already discussed friction as it applies to colliding balls, and this implementation is similar except that it affects only the x velocity. For our purposes, we will achieve simple friction by degrading the x velocity as gravity degrades the y velocity.

Taking the code from Example 5-16, in canvasApp() we create a new variable named friction. This is the amount of pixels to degrade the x velocity on every frame:

var friction = .008;

Notice that the amount is quite small. Friction does not have to be a large value to look realistic—it just needs to be applied uniformly each time drawScreen() is called. In drawScreen(), we apply friction to the x velocity like this:

ball.velocityx = ball.velocityx - ( ball.velocityx*friction);

This is the same type of proportional application of friction we used with the colliding balls, but again, this time we applied it only to the x velocity.

Figure 5-20 shows what this final version of our application looks like when executed in a web browser.

Figure 5-20. Ball bouncing with gravity, elasticity, and friction applied

Example 5-17 gives the full code for CH5EX17.html, the final code of our simple gravity, simple elasticity, and simple friction example.

Example 5-17. Gravity with a vector with bounce friction

CH5EX17: Gravity With A Vector With Bounce Friction