HTML and CSS Reference
In-Depth Information
ball = new Ball(),
vx = Math.random() * 10 - 5,
vy = Math.random() * 10 - 5,
friction = 0.1;
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var speed = Math.sqrt(vx * vx + vy * vy),
angle = Math.atan2(vy, vx);
if (speed > friction) {
speed -= friction;
} else {
speed = 0;
}
vx = Math.cos(angle) * speed;
vy = Math.sin(angle) * speed;
ball.x += vx;
ball.y += vy;
ball.draw(context);
}());
};
</script>
</body>
</html>
Here, the
friction
is set to
0.1
, and the ball is given a random velocity on the x and y axes. In the
drawFrame
function,
speed
and
angle
are calculated as we described. If
speed
is less than
friction
,
subtract; otherwise,
speed
equals zero. Finally,
vx
and
vy
are recalculated and added to the position.
Test this example several times to see it at different speeds and angles. That's how friction looks, and it
took a dozen lines of code and four trigonometry functions to accomplish. Now you're probably thinking
that it's time to look at the easy way.
Friction, the easy way
As you would expect, the easy way to simulate friction is not as accurate as the technique that was just
described, but nobody will ever notice. It consists of two lines of simple multiplication. Multiply the x and y
velocities by some fraction of 1. A number around 0.9 usually works quite well, but use your eye as the
judge. On each frame,
vx
and
vy
become 80% or 90% of what they were on previous frame. In theory, the
velocity approaches zero, but never actually reaches it. In practice, the computer only calculates such
numbers to a defined precision. But long before that, the applied motion is so small that it is indiscernible.
The good news is that the velocity never becomes negative using this method, so you don't have to check
for that. Also, the x and y velocities approach zero at the same rate, so there's no need to convert axis
velocities to angular and back.