C# XNA 鼠标位置投影到 3D 平面 [英] C# XNA Mouse position projected to 3D plane
本文介绍了C# XNA 鼠标位置投影到 3D 平面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理一个 3D XNA 项目,我已经考虑这个问题大约 2 周了.所以我决定问问你.
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.
基本上我有一个平面,我想将鼠标位置投影到那个平面上,但是如何呢?我尝试了很多方法来做到这一点,计算角度......但我发现,距离必须影响 X 位置,也许需要一些我以前从未听说过的数学运算.
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.
推荐答案
几年前我做了一些代码,返回位置为 Vector3(x,y,z),给定鼠标状态:
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 是 GraphicsDevice 的一个实例.
希望它对你有用.
这篇关于C# XNA 鼠标位置投影到 3D 平面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文