Friday, May 14, 2010

XNA Get mouse cursor ray

public Ray GetMouseCursorRay(MouseState _CurrentMouseState, Matrix _projectionMatrix, Matrix _viewMatrix)
// Create 2 positions in screenspace using the cursor position.
// 0 is as close as possible to the camera, 1 is as far away as possible.
Vector3 nearSource = new Vector3(_CurrentMouseState.X, _CurrentMouseState.Y, 0.0f);
Vector3 farSource = new Vector3(_CurrentMouseState.X, _CurrentMouseState.Y, 1.0f);

// Use Viewport. Unproject to tell what those two screen space positions would be in world space.
// We'll need the projection matrix and view matrix, which we have saved as member variables.
// We also need a world matrix, which can just be identity.
Vector3 nearPoint = _GraphicsDevice.Viewport.Unproject(nearSource, _projectionMatrix, _viewMatrix, Matrix.Identity);
Vector3 farPoint = _GraphicsDevice.Viewport.Unproject(farSource, _projectionMatrix, _viewMatrix, Matrix.Identity);

// Find the direction vector that goes from the nearPoint to the farPoint and normalize it...
Vector3 direction = farPoint - nearPoint;

// ... and then create a new ray using nearPoint as the source.
return new Ray(nearPoint, direction);