在XNA 4.0 3D中。我想拖放一个3D模型。所以,我必须在模型中检查鼠标。我的问题是我不知道改变位置并将此模型从3D评定为2D。相关的Matrix View和Matrix Projection相机? 这是我的代码: http://www.mediafire.com/?3835txmw3amj7pe
答案 0 :(得分:1)
在msdn:Selecting an Object with a Mouse上查看这篇文章。
从那篇文章:
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);
proj
和view
使用您自己的投影并相应地查看矩阵。
现在,当您拥有Ray
时,您需要BoundingBox
或BoundingSphere
(或多个)大致包含您的模型。
简单解决方案是对BoundingSphere
中的每个网格使用ModelMesh
Model.Meshes
属性。
foreach(ModelMesh mesh in model.Meshes)
{
if(Ray.Intersects(mesh.BoundingSphere))
{
//the mouse is over the model!
break;
}
}
由于每个BoundingSphere
的{{1}}将包含该网格中的所有顶点,因此可能不是网格的最精确表示,如果它不粗略< em> round (即如果它很长)。这意味着上面的代码可能会说鼠标与对象相交,当它在视觉上离开时。
另一种方法是手动创建边界卷。您可以根据需要创建ModelMesh
或BoundingBox
个对象的实例,并根据运行时要求手动更改其尺寸和位置。这需要稍微多一些工作,但并不难。