我在球之间的碰撞解决方面有问题。实际上碰撞响应是非常真实的,但是动量不是守恒的,为什么?
我使用基于此文档的算法:http ://www.vobarian.com/collisions/2dcollisions2.pdf 。
在 Java 代码中,我的算法是:
/**
* Resolve the collision creating new velocities according to physical laws.
*/
public void resolveCollisionWith(Ball ball) {
//First resolve intersection for calculate correct new velocities.
resolveIntersectionWith(ball);
//Unit normal vector uN is the unit-vector that links the two centers.
Vector uN = mPosition.subtraction(ball.getPosition()).normalize();
//Unit tangent vector uT is the unit-vector normal to uN. It's tangent to both the two balls.
Vector uT = new Vector(-uN.getY(), uN.getX());
//Project the two balls velocities onto the collision axis(uT and uN vectors).
double v1n = uN.dot(mVelocity), v1t = uT.dot(mVelocity);
double v2n = uN.dot(ball.getVelocity()), v2t = uT.dot(ball.getVelocity());
//Calculate the post collision normal velocities (tangent velocities don't change).
double v1nPost = (v1n*(mMass-ball.getMass()) + 2*ball.getMass()*v2n)/(mMass+ball.getMass());
double v2nPost = (v2n*(ball.getMass()-mMass) + 2*mMass*v1n)/(mMass+ball.getMass());
//Convert scalar velocities to vectors.
Vector postV1N = uN.multiplication(v1nPost), postV1T = uT.multiplication(v1t);
Vector postV2N = uN.multiplication(v2nPost), postV2T = uT.multiplication(v2t);
//Change the balls velocities.
mVelocity.set(postV1N.addition(postV1T));
ball.getVelocity().set(postV2N.addition(postV2T));
}
/**
* When two balls collide can occur an intersection(the distance between the centers
* is less than the sum of the radii) that dephases the response.
* The method fix this situation bringing back the two ball according to their mass.
*/
private void resolveIntersectionWith(Ball ball){
Vector n = mPosition.subtraction(ball.getPosition());
// How much the distance between centers is less than the radii's sum.
double offset = getRadius() + ball.getRadius() - n.length();
n.normalize();
n.multiply(offset);
// Bring back the two ball according to their mass.
mPosition.add(n.multiplication(ball.getMass() * 1.0 / (mMass + ball.getMass())));
ball.getPosition().subtract(n.multiplication(mMass * 1.0 / (mMass + ball.getMass())));
}
/**
* Normalizes and returns this vector.
*/
// ***INSIDE VECTOR CLASS***
public Vector normalize() {
//Avoid division by zero.
if (mX != 0 || mY != 0) {
double lenght = length();
mX /= lenght;
mY /= lenght;
}
return this;
}
谢谢!