Getting pick ray

Recommended Posts

Thought I would share since it took me a while to figure this out. No matrix multiplications or inverse matrix calculations needed. Here is how I do it (takes screen coordinates as input):
public Ray GetPickRay(int x, int y)
{
// transform screen coordinates to clip coordinates (-1, -1) - (1, 1)
float cX = 2 * x / windowWidth - 1;
float cY = 1 - 2 * y / windowHeight;

// transform clip coordinates to view space coordinates
float a = camera.Projection.ProjectionMatrix.M00;
float b = camera.Projection.ProjectionMatrix.M11;
Vector3 v = new Vector3(cX/a, cY/b, camera.Projection.Near);

// rotate and normalize
Vector3 w = camera.Rotation * v;
return new Ray(camera.Position, w.Normalize());
}


This requires that you have information about distance to near clipping plane and camera rotation and position. The ray is represented by an origin and direction vector.

Create an account

Register a new account

• Forum Statistics

• Total Topics
628334
• Total Posts
2982147

• 9
• 24
• 9
• 9
• 13