2

我的碰撞测试中有以下代码:

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/

4

1 回答 1

1

您首先更改 A 的速度,然后使用更改后的速度计算 B 的新速度。您需要使用 A 的原始速度,因此将 A 的新速度存储在临时变量中,直到您计算出速度乙:

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/

于 2012-11-18T09:25:14.970 回答