简体   繁体   English

C#XNA鼠标位置投影到3D平面

[英]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. 我正在研究一个3D XNA项目,我一直在考虑这个问题2周。 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. 我尝试了很多方法,计算角度......但我发现,距离必须影响X位置,也许需要一些我以前从未听过的数学。

I did some code few years ago which returns the position as Vector3(x,y,z), given mouse state: 几年前我做了一些代码,在给定鼠标状态的情况下返回Vector3(x,y,z)的位置:

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. device是GraphicsDevice的一个实例。

Hope it works for you. 希望对你有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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