碰撞测试中有以下代码:

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/

最佳答案

首先更改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;

演示:http://jsfiddle.net/Guffa/tLpEV/4/

10-04 15:37