I have the following method in C++:
void sphereCollisionResponse(Sphere *a, Sphe开发者_JAVA技巧re *b)
{
Vector3 U1x,U1y,U2x,U2y,V1x,V1y,V2x,V2y;
float m1, m2, x1, x2;
Vector3 v1temp, v1, v2, v1x, v2x, v1y, v2y, x(a->pos - b->pos);
x.normalize();
v1 = a->vel;
x1 = x.dot(v1);
v1x = x * x1;
v1y = v1 - v1x;
m1 = a->mass;
x = x*-1;
v2 = b->vel;
x2 = x.dot(v2);
v2x = x * x2;
v2y = v2 - v2x;
m2 = b->mass;
a->vel = Vector3( v1x*(m1-m2)/(m1+m2) + v2x*(2*m2)/(m1+m2) + v1y );
}
It's about collision response of sphere objects. I want to port it to Java, so I use the Vector2D class from here: http://goo.gl/I4R4Y and put this code in Java:
private void sphereCollisionResponse(Sphere a, Sphere b) {
double m1, m2, x1, x2;
Vector2D v1, v2, v1x, v2x, v1y, v2y;
Vector2D x = new Vector2D(a.getPos().subtract(b.getPos()));
x.normalize();
v1 = a.getVelocity();
x1 = x.dot(v1);
v1x = x.multiply(x1);
v1y = v1.subtract(v1x);
m1 = a.getMass();
x = x.multiply(-1);
v2 = b.getVelocity();
x2 = x.dot(v2);
v2x = x.multiply(x2);
v2y = v2.subtract(v2x);
m2 = b.getMass();
Vector2D av = ((v1x.multiply(m1-m2)).divide(m1+m2).add((v2x.multiply(2*m2)).divide(m1+m2))).add(v1y);
a.setVelocity(av);
}
But it turns out that when the spheres collide, the sphere I change the velocity to, disappears from the screen. So I might have trouble with the porting of the code. Can anyone more experienced in both languages check the ported code and tell me if there is something wrong?
Thanks
I'm not that good with java, but the code you're quoting seems ok, judging with my basic knowledge of java.
The problem might lie the last assignment:
Vector2D av = ((v1x.multiply(m1-m2)).divide(m1+m2).add((v2x.multiply(2*m2)).divide(m1+m2))).add(v1y);
Perhaps the resulting speed vector, av, is too big? That might explain why the sphere disappears from the screen. Can you debug it and check the value of av, or print it somewhere?
精彩评论