HTML and CSS Reference
In-Depth Information
(m1 - m0) × v1 + 2 × m0 × v0
v1Final = ----------------------------
m0 + m1
becomes this:
var vx1Final = ((ball1.mass - ball0.mass) * ball1.vx + 2 * ball0.mass * ball0.vx) /
(ball0.mass + ball1.mass);
After adding the reaction code, the complete drawFrame function ends up like this:
(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 vx0Final = ((ball0.mass - ball1.mass) * ball0.vx + 2 * ball1.mass * ball1.vx) /
(ball0.mass + ball1.mass),
vx1Final = ((ball1.mass - ball0.mass) * ball1.vx + 2 * ball0.mass * ball0.vx) /
(ball0.mass + ball1.mass);
ball0.vx = vx0Final;
ball1.vx = vx1Final;
ball0.x += ball0.vx;
ball1.y += ball1.vx;
}
ball0.draw(context);
ball1.draw(context);
}());
Because the momentum calculations reference the velocity of each ball, you need to store their results in
the temporary variables vx0Final and vx1Final , rather than assign them directly to the ball0.vx and
ball1.vx properties.
Placing the Objects
The last two lines of the reaction code we just added deserve some explanation. After you figure out the
new velocities for each ball, you add them back to the ball's position. If you recall the bouncing examples
in Chapter 6, you needed to move the ball so that it touched the edge of the wall and not get stuck.
Otherwise, it's possible that the ball can miss the edge and on subsequent frames, it can bounce back and
forth along the boundary. It's the same problem in this example, but now there are two moving objects that
you don't want embedded in each other.
 
Search WWH ::




Custom Search