从2D相机和独立分辨率获取鼠标坐标

时间:2013-01-17 16:46:46

标签: c# xna

我一直试图将David Amador的这两个样本结合起来:

http://www.david-amador.com/2010/03/xna-2d-independent-resolution-rendering/

http://www.david-amador.com/2009/10/xna-camera-2d-with-zoom-and-rotation/

一切正常,但我在获取鼠标坐标时遇到一些困难。我能够为每个单独的样本得到它们,但我考虑这两者的数学似乎是错误的。

如果我的虚拟分辨率和正常分辨率相同,则鼠标坐标是正确的。当我做像Resolution.SetVirtualResolution(1920,1080)这样的事情的时候 和Resolution.SetResolution(1280,720,false)当我移动相机时坐标慢慢失去同步。

以下是代码:

    public static Vector2 MousePositionCamera(Camera camera)
    {
        float MouseWorldX = (Mouse.GetState().X - Resolution.VirtualWidth * 0.5f + (camera.position.X) * (float)Math.Pow(camera.Zoom, 1)) /
            (float)Math.Pow(camera.Zoom, 1);

        float MouseWorldY = ((Mouse.GetState().Y - Resolution.VirtualHeight * 0.5f + (camera.position.Y) * (float)Math.Pow(camera.Zoom, 1))) /
        (float)Math.Pow(camera.Zoom, 1);

        Vector2 mousePosition = new Vector2(MouseWorldX, MouseWorldY);
        Vector2 virtualViewport = new Vector2(Resolution.VirtualViewportX, Resolution.VirtualViewportY);
        mousePosition = Vector2.Transform(mousePosition - virtualViewport, Matrix.Invert(Resolution.getTransformationMatrix()));

        return mousePosition;     
    }

在决议中我添加了这个:

virtualViewportX = (_Device.PreferredBackBufferWidth / 2) - (width / 2);
virtualViewportY = (_Device.PreferredBackBufferHeight / 2) - (height / 2);

其他所有内容都与示例代码相同。提前谢谢!

1 个答案:

答案 0 :(得分:2)

感谢David Gouveia我能够发现问题...我的相机矩阵使用了错误的数学。

我将发布我的所有代码,希望能帮助那些尝试做类似事情的人。

相机转换矩阵:

        public Matrix GetTransformMatrix()
        {
            transform = Matrix.CreateTranslation(new Vector3(-position.X, -position.Y, 0)) * Matrix.CreateRotationZ(rotation) *
                        Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) * Matrix.CreateTranslation(new Vector3(Resolution.VirtualWidth
                            * 0.5f, Resolution.VirtualHeight * 0.5f, 0));

            return transform;
        }

这也将使相机居中。以下是结合Resolution类和相机类的鼠标坐标:

    public static Vector2 MousePositionCamera(Camera camera)
    {
        Vector2 mousePosition;
        mousePosition.X = Mouse.GetState().X;
        mousePosition.Y = Mouse.GetState().Y;

        //Adjust for resolutions like 800 x 600 that are letter boxed on the Y:
        mousePosition.Y -= Resolution.VirtualViewportY;

        Vector2 screenPosition = Vector2.Transform(mousePosition, Matrix.Invert(Resolution.getTransformationMatrix()));
        Vector2 worldPosition = Vector2.Transform(screenPosition, Matrix.Invert(camera.GetTransformMatrix()));

        return worldPosition;     
    }

结合我发布/提到的所有其他代码,这应该是您实现分辨率独立性和一个非常棒的相机所需要的一切!