HTML and CSS Reference
In-Depth Information
//rotate ball1's position
x1 = dx * cos + dy * sin,
y1 = dy * cos - dx * sin,
//rotate ball0's velocity
vx0 = ball0.vx * cos + ball0.vy * sin,
vy0 = ball0.vy * cos - ball0.vx * sin,
//rotate ball1's velocity
vx1 = ball1.vx * cos + ball1.vy * sin,
vy1 = ball1.vy * cos - ball1.vx * sin;
}
}
Now perform a simple one-dimensional collision reaction with vx0 and ball0.mass and with vx1 and
ball1.mass . From the one-dimensional example presented earlier, you had the following code:
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;
You can rewrite that as follows:
var vxTotal = vx0 - vx1;
vx0 = ((ball0.mass - ball1.mass) * vx0 + 2 * ball1.mass * vx1) /
(ball0.mass + ball1.mass);
vx1 = vxTotal + vx0;
All you did was replace the ball0.vx and ball1.vx with the rotated versions vx0 and vx1 . Let's plug the
new version into the function definition:
function checkCollision (ball0, ball1) {
var dx = ball1.x - ball0.x,
dy = ball1.y - ball0.y,
dist = Math.sqrt(dx * dx + dy * dy);
if (dist < ball0.radius + ball1.radius) {
//calculate angle, sine, and cosine
var angle = Math.atan2(dy, dx),
sin = Math.sin(angle),
cos = Math.cos(angle),
//rotate ball0's position
x0 = 0,
y0 = 0,
//rotate ball1's position
x1 = dx * cos + dy * sin,
y1 = dy * cos - dx * sin,
//rotate ball0's velocity
vx0 = ball0.vx * cos + ball0.vy * sin,
vy0 = ball0.vy * cos - ball0.vx * sin,
Search WWH ::




Custom Search