Search code examples
c#-4.0xna-4.0

Check mouse in one Model or not?


In XNA 4.0 3D. I want to Drag and Drop one model 3D.So,I must check mouse in a Model or not. My problem is I don't know change position and rate this Model from 3D to 2D. It's related Matrix View and Matrix Projection of camera?? This is my code: http://www.mediafire.com/?3835txmw3amj7pe


Solution

  • Check out this article on msdn: Selecting an Object with a Mouse.

    From that article:

    MouseState mouseState = Mouse.GetState();
    int mouseX = mouseState.X;
    int mouseY = mouseState.Y;
    
    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);
    
    // 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);
    

    For proj and view use your own projection and view matrices accordingly.

    Now when you have your Ray, you need to have a BoundingBox or a BoundingSphere (or multiple) that are roughly encompassing your model.

    A simple solution is to use BoundingSphere properties of ModelMesh for each mesh in your Model.Meshes.

    foreach(ModelMesh mesh in model.Meshes)
    {
        if(Ray.Intersects(mesh.BoundingSphere))
        {
            //the mouse is over the model!
            break;
        }
    }
    

    Since BoundingSphere of each ModelMesh is going to encompass all vertices in that mesh, it might not be the most precise representation of the mesh if it is not roughly round (i.e. if it is very long). This means that the above code could be saying that the mouse intersects the object, when visually it is way off.

    The alternative is to create your bounding volumes manually. You make instances of BoundingBox or BoundingSphere objects as suits your need, and manually change their dimensions and positions based on runtime requirements. This requires slightly more work, but it isn't hard.