Hello! I'm new to bullet and I'm trying to get ray casting working for picking objects. For now I'm using simple test shapes but I get unexpected results. Each object I'm trying to pick is created like this:
Code:
// create a boxShape with size 2, 2, 2
btCollisionShape *shape = new btBoxShape(btVector3(1, 1, 1));
btCollisionObject *body = new btCollisionObject();
body->setCollisionShape(shape);
body->setUserPointer(this);
// world is a btDynamicsWorld *
world->addCollisionObject(body);
The position of this object is updated as follows:
Code:
btTransform pos;
pos.setIdentity();
// mat is a btScalar * containing an OpenGL type matrix
pos.setFromOpenGLMatrix(mat);
// apply the transform to the object
body->setWorldTransform(pos);
And the ray cast is performed like this:
Code:
btCollisionWorld::ClosestRayResultCallback resultCallback(from, to);
world->rayTest(from, to, resultCallback);
if (resultCallback.hasHit())
{
// some object was hit
}
For debugging purposes I request all collision objects from the world (with getCollisionObjectArray();), print their origins, the from and to vectors and the calculated world xy coordinate at the z coordinate of the origin of the object. Actual output is shown below:
Code:
// a hit was expected given this ray, the objects origin and the size of the object
from: [-0.155175, -0.020690, 27.001001]
to: [-776.752686, -103.567055, -4972.657227]
obj[0], origin: [-4.000000, 0.000000, 0.000000] // according to world->getCollisionObjectArray().at(0).getWorldTransform().getOrigin();
obj[0], calculated ray xy coordinate @z==0.000000: [-4.349244, -0.579899] // debug, calculated myself using from/to/origin.z
resultCallback.hasHit(): false
// again, I would have expected a hit
from: [-0.143106, 0.000000, 27.001001]
to: [-716.338684, 0.000000, -4972.657227]
obj[0], origin: [-4.000000, 0.000000, 0.000000] // according to world->getCollisionObjectArray().at(0)..getWorldTransform().getOrigin();
obj[0], calculated ray xy coordinate @z==0.000000: [-4.010970, 0.000000] // debug, calculated myself using from/to/origin.z
resultCallback.hasHit(): false
I was able to get some hits in case the object was very close to the center of the screen. But also in this case the hit area was generally smaller than the size of the object I was trying to hit. Anything obvious I'm doing wrong here? Are there any important steps in setting up the btDynamicsWorld which I could be missing?
Any help would be greatly appreciated!
one more thing: the objects are static (they don't move, the camera doesn't move either but that doesn't really matter I guess; only for the result of my unproject code).