Xna 4.0 C#点击模型教程?

时间:2013-06-08 16:30:47

标签: c# xna xna-4.0

我最近能够在屏幕上创建模型,并且还添加了边界框碰撞检测。我现在要做的是,当某个模型被点击时会发生什么事情,有没有人知道这方面有什么好的教程?

1 个答案:

答案 0 :(得分:3)

您需要从相机和鼠标坐标投射 Ray ,并测试它是否与您的边界框相交。您可以通过将相机的视图和投影矩阵传递给此函数来创建光线:

 public Ray CalculateCursorRay(Matrix projectionMatrix, Matrix viewMatrix)
    {
        //Position is your mouse position
        Vector3 nearSource = new Vector3(Position, 0f);
        Vector3 farSource = new Vector3(Position, 1f);

        Vector3 nearPoint = GraphicsDevice.Viewport.Unproject(nearSource,
            projectionMatrix, viewMatrix, Matrix.Identity);

        Vector3 farPoint = GraphicsDevice.Viewport.Unproject(farSource,
            projectionMatrix, viewMatrix, Matrix.Identity);

        Vector3 direction = farPoint - nearPoint;
        direction.Normalize();

        return new Ray(nearPoint, direction);
    }

然后您可以调用 yourBox.Intersects(yourRay),如果没有交叉点,将返回 null
整个代码取自this MSDN sample