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-21 shows what this final version of our application looks like when executed in a web browser. ...
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.