Hi All,
I am having a lot of difficulty with collision detection. Actually, I’m not certain if it’s a problem with collision detection specifically or something I just don’t understand about OpenGL. I have adapted Oleg Dopertchouk’s example from “Simple Bounding-Sphere Collision Detection” for a Java game using JOGL. ( Thanks to Oleg! ) Here is my method:
boolean sphereTest(AbstractGameObject obj1, AbstractGameObject obj2)
{
// Relative velocity
Vector3D dv = Vector3D.substract(obj2.getVelocity(),obj1.getVelocity());
// Relative position
Vector3D dp = Vector3D.substract(obj2.getPosition(),obj1.getPosition());
//Minimal distance squared
float r = (obj1.getWidth() / 2) + (obj2.getWidth() / 2);
//dP^2-r^2
float pp = dp.x * dp.x + dp.y * dp.y + dp.z * dp.z - r*r;
//(1)Check if the spheres are already intersecting
if ( pp < 0 ) return true;
//dP*dV
float pv = dp.x * dv.x + dp.y * dv.y + dp.z * dv.z;
//(2)Check if the spheres are moving away from each other
if ( pv >= 0 ) return false;
//dV^2
float vv = dv.x * dv.x + dv.y * dv.y + dv.z * dv.z;
//(3)Check if the spheres can intersect within 1 frame
if ( (pv + vv) <= 0 && (vv + 2 * pv + pp) >= 0 ) return false;
//tmin = -dPdV/dV2
//the time when the distance between the spheres is minimal
float tmin = -pv/vv;
//Discriminant/(4dV^2) = -(dp^2-r^2+dPdV*tmin)
return ( pp + pv * tmin > 0 );
}
Now this works like a charm if obj2 is sitting at 0.0f,0.0f,0.0f, but the further down on the screen obj2 is ( for example -.5f on the y axis ) obj1 collides sooner. Way to soon. And the further down it is the sooner it collides. If obj2 is further up the screen from the center ( for example .5f on the y axis ) then the collision happens way too late. It’s very odd to me. The output of my tracing is:
Ball 0.0,-0.57959735,0.0 w=0.06 h=0.06 collided with TestBlocker 0.0,-0.5,0.0 w=0.1 h=0.05
Unless I am missing something, the above output looks correct, however the 2 objects are miles from each other. Can anyone give me hints as to what the problem might be?
Many thanks!
-B