首页 > 解决方案 > 如何在 MonoGame 中向 2D 中的鼠标位置缩放

问题描述

我有以下相机类:

public Vector2 Position { get; set; } = Vector2.Zero;
public float Rotation { get; set; } = 0.0f;
public float Zoom
{
    get
    {
        // Negative zoom will flip the image
        if (_zoom < 0.1f)
        {
            _zoom = 0.1f;
        }
        return _zoom;
    }
    set
    {
        _zoom = value;
        // Negative zoom will flip the image
        if (_zoom < 0.1f)
        {
            _zoom = 0.1f;
        }
    }
}

public Matrix Transform(Viewport viewport)
{
    int viewportWidth = viewport.Width;
    int viewportHeight = viewport.Height;

    return
        Matrix.CreateTranslation(new Vector3(-Position.X - viewportWidth / 2, -Position.Y - viewportHeight / 2, 0)) * // Translation Matrix
        Matrix.CreateRotationZ(Rotation) * // Rotation Matrix
        Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) * // Scale Matrix
        Matrix.CreateTranslation(new Vector3(viewportWidth / 2, viewportHeight / 2, 0)); // Origin/Offset Matrix
}

public void Move(Vector2 amount)
{
    Position += amount;
}

以及一种Update()检查用户从键盘和鼠标输入到某些事物的方法,例如移动、旋转、缩放。

问题

从我的变换矩阵中可以看出,当我放大/缩小(增量或减量_zoom)时,我正在向一个固定的原点进行缩放——我的屏幕中心。

当它向鼠标光标缩放时,我怎样才能做到这一点?

我阅读了一些类似问题的答案,但我无法为我的相机实现它。任何帮助表示赞赏。

标签: c#xnazoomingmonogame

解决方案


在缩放之前应用另一个平移以使缩放居中于鼠标点。

public Matrix Transform(Viewport viewport)
{
    int viewportWidth = viewport.Width;
    int viewportHeight = viewport.Height;

    return
        Matrix.CreateTranslation(new Vector3(-Position.X - viewportWidth / 2, -Position.Y - viewportHeight / 2, 0)) * // Translation Matrix
        Matrix.CreateRotationZ(Rotation) * // Rotation Matrix
        Matrix.CreateTranslation(new Vector3(-mouseState.X - viewportWidth / 2, -mouseState.Y - viewportHeight / 2, 0)) * //Mouse Translation Matrix
        Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) * // Scale Matrix
        Matrix.CreateTranslation(new Vector3(viewportWidth / 2, viewportHeight / 2, 0)); // Origin/Offset Matrix
}

推荐阅读