How To: Detect Whether a User Clicked a 3D Object
|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
Get the current state of the mouse by using GetState.
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);
Create a Ray starting at the near point and pointing toward the far point.
- 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.