HTML and CSS Reference
In-Depth Information
//rotate ball1's velocity
vx1 = ball1.vx * cos + ball1.vy * sin,
vy1 = ball1.vy * cos - ball1.vx * sin ,
//collision reaction
vxTotal = vx0 - vx1;
vx0 = ((ball0.mass - ball1.mass) * vx0 + 2 * ball1.mass * vx1) /
(ball0.mass + ball1.mass);
vx1 = vxTotal + vx0;
x0 += vx0;
x1 += vx1;
}
}
This code also adds the new x velocities to the x positions, to move them apart, as in the one-dimensional
example.
Now that you have updated post-collision positions and velocities, rotate everything back. Start by getting
the unrotated, final positions:
//rotate positions back
var x0Final = x0 * cos - y0 * sin,
y0Final = y0 * cos + x0 * sin,
x1Final = x1 * cos - y1 * sin,
y1Final = y1 * cos + x1 * sin;
Remember to reverse the + and - in the rotation equations, as you are going in the other direction now.
These “final” positions are actually not quite final. They are in relation to the pivot point of the system,
which is ball0 's original position. You need to add all of these to ball0 's position to get the actual
coordinate positions. Let's do ball1 first, so that it uses ball0 's original position, not the updated one:
//adjust positions to actual screen positions
ball1.x = ball0.x + x1Final;
ball1.y = ball0.y + y1Final;
ball0.x = ball0.x + x0Final;
ball0.y = ball0.y + y0Final;
Last, but not least, rotate back the velocities. These can be applied directly to the balls' vx and vy
properties:
//rotate velocities back
ball0.vx = vx0 * cos - vy0 * sin;
ball0.vy = vy0 * cos + vx0 * sin;
ball1.vx = vx1 * cos - vy1 * sin;
ball1.vy = vy1 * cos + vx1 * sin;
Finally, take a look at the entire completed function:
function checkCollision (ball0, ball1) {
var dx = ball1.x - ball0.x,
dy = ball1.y - ball0.y,
dist = Math.sqrt(dx * dx + dy * dy);
Search WWH ::




Custom Search