HTML and CSS Reference
In-Depth Information
Now that's better than that horrible double formula. Also, since the formula for ball1.vx doesn't reference
ball0.vx anymore, you can get rid of the temporary variables. Here's the revised drawFrame function
(from document 02-billiard-2.html ):
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ball0.x += ball0.vx;
ball1.x += ball1.vx;
var dist = ball1.x - ball0.x;
if (Math.abs(dist) < ball0.radius + ball1.radius) {
var vxTotal = ball0.vx - ball1.vx;
ball0.vx = ((ball0.mass - ball1.mass) * ball0.vx + 2 * ball1.mass * ball1.vx) /
(ball0.mass + ball1.mass);
ball1.vx = vxTotal + ball0.vx;
ball0.x += ball0.vx;
ball1.y += ball1.vx;
}
ball0.draw(context);
ball1.draw(context);
}());
We've gotten rid of quite a few math operations and still have the same result—not bad.
This isn't one of those formulas that you're necessarily going to understand inside out. You might not
memorize it, but at least you know you can always find the formula here. Whenever you need it for your
own programs, just pull this topic out and copy it!
Conservation of Momentum on Two Axes
Take a deep breath, because you're going to the next level. So far, you've applied a long-winded formula,
but it's pretty much plug-and-play. You take the mass and the velocity of the two objects, plug them into
the formula, and get your result.
Now we throw one more layer of complexity into it—another dimension. You use coordinate rotation to do
it, but let's take a look at why.
Understanding the Theory and Strategy
Figure 11-2 illustrates the example you just saw: collision in one dimension.
 
Search WWH ::




Custom Search