Export (0) Print
Expand All

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

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.
Bb203905.note(en-us,XNAGameStudio.31).gifNote
This example applies only to Windows development. The Mouse and MouseState objects are not supported on Xbox 360.

The Complete Sample

The code in the topic shows you the technique. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.

Detecting Whether a User Clicked a 3D Object

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.

  4. 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.

  5. For both points, pass Unproject the current projection matrix, the 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 = GraphicsDevice.Viewport.Unproject(nearsource, 
        proj, view, world);
    
    Vector3 farPoint = GraphicsDevice.Viewport.Unproject(farsource, 
        proj, view, world);
    
  6. 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);
    
  7. Use Intersects to loop through the objects in the world to check whether the Ray intersects each object.

  8. If the Ray intersects 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.

  9. When you completely loop through the objects, the last object stored will be the closest object underneath the area the user clicked.

Community Additions

ADD
Show:
© 2014 Microsoft