鼠标位置到世界位置。和鼠标位置到屏幕重新缩放的世界位置

Mouse position to World Position. And Mouse position to Screen Re-scaled World Position

所以我正在使用相机(View Matrix)来移动瓷砖世界。 在 XNA(MONOGAME)中

我正在使用此代码获取原始鼠标位置:

MouseState ms = Mouse.GetState();
Vector2 mousePosition = new Vector2(ms.X, ms.Y);

现在,如果我将 X 除以 TILE_WIDTH,将 Y 除以 TILE_WIDTH,它就会给我可以从数组中获取的图块。但是一旦我移动矩阵它就会偏移。如何将世界偏移量添加到我的鼠标位置?

还有一个问题。当我调整 window 大小时。鼠标将偏移更多。无论如何解决这个问题。所以它可以在全屏模式下工作 window 在鼠标可以转换为 worldPosition 的任何分辨率下?

我的渲染:

spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, c2d.get_transformation(GraphicsDevice));
spriteBatch.End();

我的视图矩阵:

    public Matrix get_transformation(GraphicsDevice graphicsDevice)
    {
        _transform =       // Thanks to o KB o for this solution
          Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
                                     Matrix.CreateRotationZ(Rotation) *
                                     Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
                                     Matrix.CreateTranslation(new Vector3(graphicsDevice.Viewport.Width * 0.5f, 
                                     graphicsDevice.Viewport.Height * 0.5f, 0));
        return _transform;
    }

我的瓷砖获取方式:

 tile[(int)worldPosition.Y / TILE_SIZE, (int)worldPosition.X /  TILE_SIZE].color = Color.Red;

我尝试过的东西:

Vector2 worldPosition = Vector2.Transform(mousePosition, Matrix.Invert(viewMatrix));

(https://gamedev.stackexchange.com/questions/21681/how-to-get-mouse-position-relative-to-the-map)

TL;DR

即使我调整 window 移动我的 camera2D、缩放、X、Y,我如何在世界视图中获得我的鼠标位置。

您需要"unapply"矩阵到鼠标位置。为此,您首先必须反转矩阵:

Matrix inverseTransform = Matrix.Invert(_transform);

之后,您可以像这样变换鼠标向量:

Vector2 mouseInWorld = Vector2.Transform(new Vector2(ms.X, ms.Y), inverseTransform);