3 out of 4 rated this helpful - Rate this topic

# How To: Detect Whether a User Clicked a 3D Object

XNA Game Studio 2.0
This example demonstrates how to check whether the mouse is positioned over a 3D object by creating a ray starting at the camera's near clipping plane and ending at its far clipping plane.
Note
This example applies only to Windows development. The Mouse and MouseState objects are not supported on Xbox 360.

# The Complete Sample

The code in this tutorial illustrates the technique described in the text. A complete code sample for this tutorial is available for you to download, including full source code and any additional supporting files required by the sample.

### To check whether the mouse is positioned over a 3D object

1. Get the current state of the mouse by using GetState.

```MouseState mouseState = Mouse.GetState();
```
2. Get the current screen coordinates of the mouse from X and Y.

```int mouseX = mouseState.X;
int mouseY = mouseState.Y;
```
3. Using Viewport.Unproject, determine points in world space on the near and far clip plane. For the point on the near plane, pass a source vector with x and y set to the mouse position and z set to 0. For the point on the far plane, pass a source vector with x and y set to the mouse position and z set to 1. For both points, pass Unproject the current projection matrix and view matrix and a translation matrix for the point (0,0,0).

```Vector3 nearsource = new Vector3((float)mouseX, (float)mouseY, 0f);
Vector3 farsource = new Vector3((float)mouseX, (float)mouseY, 1f);

Matrix world = Matrix.CreateTranslation(0, 0, 0);

Vector3 nearPoint = graphics.GraphicsDevice.Viewport.Unproject(nearsource, proj, view, world);

Vector3 farPoint = graphics.GraphicsDevice.Viewport.Unproject(farsource, proj, view, world);
```
4. Create a Ray starting at the near point and pointing toward the far point.

```// Create a ray from the near clip plane to the far clip plane.
Vector3 direction = farPoint - nearPoint;
direction.Normalize();
Ray pickRay = new Ray(nearPoint, direction);
```
5. Loop through the objects in the world using Intersects to check whether the Ray intersects each object. If the Ray does intersect an object, check whether it is the closest object intersected so far. If it is, store the object and the distance at which it was intersected, replacing any previously stored object. When the objects have been completely looped through, the last object stored will be the closest object underneath the area the user clicked.