我的碰撞测试中有以下代码:
if (Math.pow(A.x - B.x, 2) + Math.pow(A.y - B.y, 2) <= Math.pow(A.radius + B.radius, 2)) {
A.x_vel = (A.x_vel * (A.mass - B.mass) + (2 * B.mass * B.x_vel)) / (A.mass + B.mass);
A.y_vel = (A.y_vel * (A.mass - B.mass) + (2 * B.mass * B.y_vel)) / (A.mass + B.mass);
B.x_vel = (B.x_vel * (B.mass - A.mass) + (2 * A.mass * A.x_vel)) / (A.mass + B.mass);
B.y_vel = (B.y_vel * (B.mass - A.mass) + (2 * A.mass * A.y_vel)) / (A.mass + B.mass);
A.x = A.x + A.x_vel;
A.y = A.y + A.y_vel;
B.x = B.x + B.x_vel;
B.y = B.y + B.y_vel;
}
结果是圆圈粘在一起。我怎么解决这个问题?在http://jsfiddle.net/tLpEV/3/进行演示(全屏:http://fiddle.jshell.net/tLpEV/3/show/)
答案 0 :(得分:1)
您首先更改A的速度,然后使用更改的速度计算B的新速度。您需要使用A的原始速度,因此将A的新速度存储在临时变量中,直到您计算出来B的速度:
var ax = (A.x_vel * (A.mass - B.mass) + (2 * B.mass * B.x_vel)) / (A.mass + B.mass);
var ay = (A.y_vel * (A.mass - B.mass) + (2 * B.mass * B.y_vel)) / (A.mass + B.mass);
B.x_vel = (B.x_vel * (B.mass - A.mass) + (2 * A.mass * A.x_vel)) / (A.mass + B.mass);
B.y_vel = (B.y_vel * (B.mass - A.mass) + (2 * A.mass * A.y_vel)) / (A.mass + B.mass);
A.x_vel = ax;
A.y_vel = ay;
A.x = A.x + A.x_vel;
A.y = A.y + A.y_vel;
B.x = B.x + B.x_vel;
B.y = B.y + B.y_vel;