您好我试图实现一个简单的球碰撞检测算法如下解释:http://wp.freya.no/3d-math-and-physics/simple-sphere-sphere-collision-detection-and-collision-response/碰撞响应方法
所以我实现的方法来检查,如果发生碰撞:
private boolean advancedSphereSphere(Sphere a, Sphere b) {
Vector2D s = a.getPos().sub(b.getPos());
Vector2D v = a.getVelocity().sub(b.getVelocity());
float r = a.getRadius() + b.getRadius();
double c1 = s.dot(s) - r*r;
if(c1 < 0.0) {
timeToCollision = .0f;
return true;
}
double a1 = v.dot(v);
if(a1 < 0.00001f) {
return false;
}
double b1 = v.dot(s);
if(b1 >= 0.0) {
return false;
}
double d1 = b1*b1 - a1*c1;
if(d1 < 0.0) {
return false;
}
timeToCollision = (float) (-b1 - Math.sqrt(d1)/a1);
return true;
}
然后,我有一个的onDraw方法该循环绘制所有必要的元素,如下:
protected void onDraw(Canvas canvas) {
flowPhysics(false);
for(Sphere s : mSpheres) {
s.draw(canvas);
}
invalidate();
}
和flowPhysics(boolean)方法出现该问题,在这一行:
for(int i=0; i < mSpheres.size(); ++i) {
for(int j=i+1; j < mSpheres.size(); ++j) {
Sphere a = mSpheres.get(i);
Sphere b = mSpheres.get(j);
if(advancedSphereSphere(a, b) || step) {
if(timeToCollision < dt && !step) {
flowPhysics(true);
}
if(step) {
sphereCollisionResponse(a, b);
}
}
}
}
当advancedSphereSphere()时,第一球消失了,我查了一下,发现这个问题是在第一行的方法称为:如果我把别的东西在这里
Vector2D s = a.getPos().sub(b.getPos());
和不要从矢量中减去b,它会画出球(但不会发生碰撞)。上面的Java代码大多是从这里移植的代码:http://wp.freya.no/websvn/filedetails.php?repname=Public&path=%2Fopengl%2Fcollisiondetect%2Fcollisiondetect.cpp
你能告诉我什么是问题吗?
感谢
UPDATE
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().sub(b.getPos()));
x.normalize();
v1 = new Vector2D(a.getVelocity());
x1 = x.dot(v1);
v1x = new Vector2D(x.multiply(x1));
v1y = new Vector2D(v1.sub(v1x));
m1 = a.getMass();
x = new Vector2D(x.multiply(-1));
v2 = new Vector2D(b.getVelocity());
x2 = x.dot(v2);
v2x = new Vector2D(x.multiply(x2));
v2y = new Vector2D(v2.sub(v2x));
m2 = b.getMass();
Vector2D nn = new Vector2D(v1x.multiply(m1-m2));
Vector2D mm = new Vector2D(nn.divide(m1+m2));
Vector2D tt = new Vector2D(v2x.multiply(2*m2));
Vector2D rr = new Vector2D(tt.divide(m1+m2));
Vector2D gg = new Vector2D(mm.add(rr));
Vector2D ss = new Vector2D(gg.add(v1y));
Vector2D nva = ss;
a.setVelocity(nva);
Vector2D nvb = new Vector2D(v1x.multiply(2*m1).divide(m1+m2).add(v2x.multiply(m2-m2).divide(m1+m2).add(v2y)));
b.setVelocity(nvb);
}
“第一个球体消失” - 是因为你的系统认为它与自身相撞? “doPhysics”和“sphereCollisionResponse”做了什么? –
“step”定义在哪里?它是如何定义的? – Dave
step是flowPhysics(布尔步骤)中的参数,就像递归工作的帮助器一样。 (在onDraw中,你可以看到,我有flowPhysics(false),然后我在flowPhysics()本身有递归如果发生碰撞,我将它设置为true(flowPhysics(true))。 – Tzanter