HTML and CSS Reference
In-Depth Information
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 ex-
ample, 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
onlythe x velocity.Forourpurposes,wewill achieve simple friction bydegrading the x velo-
city as gravity degrades the y velocity.
Taking the code from Example 5-16 , in canvasApp() we create a new variable named fric-
tion . This is the amount of pixels to degrade the x velocity on every frame:
var
var friction = . 008 ;
Noticethattheamountisquitesmall.Frictiondoesnothavetobealargevaluetolookrealist-
ic—itjustneedstobeapplieduniformlyeachtime drawScreen() iscalled.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.
Search WWH ::




Custom Search