C# XNA Mouse position projected to 3D plane

2019-07-02 00:53发布

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.

标签: c# 3d xna
1条回答
神经病院院长
2楼-- · 2019-07-02 01:42

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.

查看更多
登录 后发表回答