本文介绍了XNA - 使用带有旋转/缩放/平移的 2d 相机系统获取鼠标坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有这个转换矩阵的 2d 相机:

I have a 2d Camera with this translation matrix:

        Transform = Matrix.CreateTranslation(new Vector3(-Position.X, -Position.Y, 0)) *
                     Matrix.CreateRotationZ(Rotation) *
                     Matrix.CreateScale(new Vector3(Scale, Scale, 0)) *
                     Matrix.CreateTranslation(new Vector3((GraphicsDevice.Viewport.Width * 0.5f), (GraphicsDevice.Viewport.Height * 0.5f), 0));

适用于原点为相机中心的旋转/缩放.

Which works for Rotation/Zoom where the origin is the center of the camera.

现在我正在尝试获取世界中的鼠标坐标.

Now I am trying to get the mouse coordinates in the world.

我尝试只使用逆变换,但这只会导致 NaN 错误.我猜我需要为鼠标坐标设置另一个平移矩阵,与当前坐标相反,但我不知道这是如何设置的

I tried just using an inverse transformation, but that just resulted in NaN errors.I am guessing I need to set up another translation matrix for the mouse coordinates, a reverse of the current one, but I can't figure out how this is set up

我有这个,

MousePosition = new Vector2((Mouse.GetState().X - DrawTransform.Translation.X) * (1/Gamecode.Camera1.Scale), (Mouse.GetState().Y - DrawTransform.Translation.Y) *(1/Gamecode.Camera1.Scale));

MousePosition = new Vector2((Mouse.GetState().X - DrawTransform.Translation.X) * (1 / Gamecode.Camera1.Scale), (Mouse.GetState().Y - DrawTransform.Translation.Y) * (1 / Gamecode.Camera1.Scale));

但这并没有考虑到轮换

推荐答案

通常,找到矩阵的逆比手动计算客户端到世界的位置更容易、更可靠.

Generally it's easier and more robust to find the inverse of your matrix, than to calculate the client-to-world position by hand.

您的矩阵的问题 - 您无法得到逆矩阵的原因是您将 Z 轴缩小到零.

The problem with your matrix - the reason you cannot get the inverse, is that you're scaling the Z axis down to zero.

Matrix.CreateScale(new Vector3(Scale, Scale, 0))

这意味着您已在单个轴上展平了整个空间.因此,当您尝试在该空间(客户空间)中取一个点并将其返回到原始空间(世界空间)时,您返回的实际上是一条沿 Z 轴延伸的线.这就是为什么你会得到 NaN 的原因.(或者你可以说 - 你引入了除以零.)

This means that you've flattened your entire space on a single axis. So when you try to take a single point in that space (client space) and return it to the original space (world space) what you get back is actually a line stretching along the Z axis. This is why you get NaNs back. (Or you could just say - you've introduced a division by zero.)

矩阵逆函数不知道您只是在使用平面的 2D 平面.XNA 的矩阵是 3D 的.

The matrix inverse function doesn't know that you're just using a flat, 2D plane. XNA's matrices are 3D.

解决方法是将您的矩阵更改为:

The fix is to change your matrix to this:

Matrix.CreateScale(Scale)

然后尝试找到逆.

这篇关于XNA - 使用带有旋转/缩放/平移的 2d 相机系统获取鼠标坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 06:39