1

我一直在尝试将 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);

其他一切都与示例代码相同。提前致谢!

4

1 回答 1

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;
        }

这也将使相机居中。以下是结合分辨率类和相机类获取鼠标坐标的方法:

    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;     
    }

结合我发布/提到的所有其他代码,这应该是实现分辨率独立性和出色相机所需的全部内容!

于 2013-01-19T19:57:20.897 回答