简体   繁体   中英

C# XNA Mouse position projected to 3D plane

I'm working on a 3D XNA project, and I've been thinking about this problem for like 2 weeks. So I just decided to ask you.

Basically I have a flat plane and i want to project the mouse position to that plane, but how? I tried many ways to do it, calculated angles... But i figured out, that the distance must effect on the X position, maybe some math is needed what I've never heard before.

I did some code few years ago which returns the position as Vector3(x,y,z), given mouse state:

private Vector3 FindWhereClicked(MouseState ms)
{
    Vector3 nearScreenPoint = new Vector3(ms.X, ms.Y, 0);
    Vector3 farScreenPoint = new Vector3(ms.X, ms.Y, 1);
    Vector3 nearWorldPoint = device.Viewport.Unproject(nearScreenPoint, cam.projectionMatrix, cam.viewMatrix, Matrix.Identity);
    Vector3 farWorldPoint = device.Viewport.Unproject(farScreenPoint, cam.projectionMatrix, cam.viewMatrix, Matrix.Identity);

    Vector3 direction = farWorldPoint - nearWorldPoint;

    float zFactor = -nearWorldPoint.Y / direction.Y;
    Vector3 zeroWorldPoint = nearWorldPoint + direction * zFactor;

    return zeroWorldPoint;
}
  • device is an instance of GraphicsDevice.

Hope it works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM