HTML and CSS Reference
In-Depth Information
The only alterations to the code (which can be found in the document 07-friction-2.html ) is adjusting
the friction variable to 0.95 and the following changes to the drawFrame function:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
vx *= friction;
vy *= friction;
ball.x += vx;
ball.y += vy;
ball.draw(context);
}());
Now, that's certainly easier! Test this version a number of times and get a feel for it. The motion looks
virtually identical to the “correct” method, but at a fraction of the calculation cost. And the average viewer
won't even notice.
Because these methods continue to add the friction value to the ball's position after it has any visual effect,
you can save some calculations by checking whether the number is larger than a designated minimum
distance before applying the friction, like so:
if (Math.abs(vx) > 0.001) {
vx *= friction;
ball.x += vx;
}
Math.abs returns the absolute value of vx. The friction variable is a fairly arbitrary number (within a
range) and really depends on how the animation “feels” to you. Experiment with different values to see
how it affects the motion characteristics.
Friction applied
We return to our familiar spaceship simulation and apply some friction to that universe. In example 08-
ship-sim-friction.html , take the flle 03-ship-sim-2.html and add a friction variable:
var friction = 0.97;
Then, change the drawFrame function to the following:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ship.rotation += vr * Math.PI / 180;
var angle = ship.rotation,
ax = Math.cos(angle) * thrust,
ay = Math.sin(angle) * thrust,
left = 0,
right = canvas.width,
top = 0,
bottom = canvas.height;
 
Search WWH ::




Custom Search