• 15
• 15
• 11
• 9
• 10

# Ray picking (Objects with various World matrix)

This topic is 4197 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello, I'm writing the mouse picking in my engine, here is the code for it :
public RayFromMouse(Point p_MousePosition)
{

_RayStart = new Vector3(p_MousePosition.X, p_MousePosition.Y, 0f);
_RayEnd = new Vector3(p_MousePosition.X, p_MousePosition.Y, 1f);

Matrix ObjectWorld;
ObjectWorld = Matrix.Identity;

_RayStart = Vector3.Unproject(_RayStart, DeviceManager.NoaDevice.Viewport, CameraManager.Projection, CameraManager.View, ObjectWorld);
_RayEnd = Vector3.Unproject(_RayEnd, DeviceManager.NoaDevice.Viewport, CameraManager.Projection, CameraManager.View, ObjectWorld);

_RayDir = _RayEnd - _RayStart;
_RayDir.Normalize();

}

public bool Intersect()
{

IntersectInformation info;
bool result;

result = Geometry.IntersectTri(new Vector3(0, 2, 0), new Vector3(1, 0, 0), new Vector3(-1, 0, 0), _RayStart, _RayDir, out info);

return result;
}


In this code I'm testing the Intersect against a simple triangle. This code works really well but only for the objects that have their world matrix equal to identity. If it's not the case then I have to change the ObjectWorld = Matrix.Identity to ObjectWorld = MyObjectToTest.World matrix. But in this case I'm oblige to call both RayFromMouse() and Intersect() for every objects. I would like to be able to call only Intersect() for each objects. how do you manage the picking in a case where nearly every object in your scene does have a custom World Matrix ? Do you recompute the ray for every Object that needs to be tested ? Tx you for your help !

##### Share on other sites
It is possible to unproject the ray only once by supplying Matrix.Identity to the Unproject methods and use this world-space ray for intersections on your meshes. But you'll still have to translate this ray to the model's space to perform the intersection test. It would indeed improve performance since it elimniates a few matrix multiplications, but it makes the picking code less tidy imho (and the Unproject methods probably also are pretty optimized already).

I'd just use Unproject for each object with its appropriate world matrix. The real bottleneck is in the actual intersection test, so the overhead shouldn't even be noticable. If you still want to optimize the ray unprojection though, this picking info on Toymaker's site might be useful.

Hope this helps :)