HTML and CSS Reference
In-Depth Information
So, how do you implement friction in code? There are two ways, and like most things in life, you have the
right way and the easy way. The easy way is preferred in this topic, but you'll see examples of both and
you can make up your own mind.
Friction, the right way
Friction is subtractive of velocity, which means you have a certain value for friction, and you subtract that
from your velocity. More precisely, you must subtract it from the magnitude, or speed, of the velocity; you
can't just subtract the friction from the x axis and y axis separately. If you do that for an object traveling at
an angle, one of the component velocities will reach zero before the other, and the object will continue
moving either vertically or horizontally, which looks strange.
What you need to do is find the angular velocity in terms of speed and direction (if you don't have it
already). To find the speed, take the square root of vx squared plus vy squared (yes, that's the
Pythagorean Theorem, which you should recognize from Chapter 3). To find the angle, you calculate
Math.atan2(vy, vx) , which looks like this:
var speed = Math.sqrt(vx * vx + vy * vy),
angle = Math.atan2(vy, vx);
Then you can subtract the friction from the speed, but you want to make sure you don't send the speed
into negative values, which reverses the velocity. If your friction is greater than your speed, the speed
becomes zero. Here is the code for that calculation:
if (speed > friction) {
speed -= friction;
} else {
speed = 0;
}
At that point, you need to convert the angular velocity back into vx and vy , using sine and cosine, like so:
vx = Math.cos(angle) * speed;
vy = Math.sin(angle) * speed;
Here's how it looks all together in the document 06-friction-1.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Friction 1</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
 
Search WWH ::




Custom Search