繁体   English   中英

XNA 4.0:2D摄像机Y和X方向错误

[英]XNA 4.0: 2D Camera Y and X are going in wrong direction

因此,我知道关于为XNA构建2D相机存在一些问题/答案,但是人们似乎很乐意发布自己的代码而无需解释。 我正在寻找更多关于我做错事情的解释。

首先,我了解整个世界->视图->投影->屏幕变换。

我的目标是使一个相机对象位于视口的中心,并且当相机的位置向上移动时,它与在视口中向上移动相关;当相机位置向右移动时,它与在视口中向右移动相关。

我很难实现该功能,因为视口的Y值是反转的。

//In Camera Class
private void UpdateViewTransform()
{
//My thinking here was that I would create a projection matrix to center the camera and then flip the Y axis appropriately
     Matrix proj = Matrix.CreateTranslation(new Vector3(_viewport.Width * 0.5f, _viewport.Height * 0.5f, 0)) * 
                   Matrix.CreateScale(new Vector3(1f, -1f, 1f));

//Here is the camera Matrix. I have to give the Inverse of this matrix to the Spritebatch I believe since I want to go from World Coordinates to Camera Coordinates
     _viewMatrix = Matrix.CreateRotationZ(_rotation) *
                  Matrix.CreateScale(new Vector3(_zoom, _zoom, 1.0f)) *
                  Matrix.CreateTranslation(_position.X, _position.Y, 0.0f);

     _viewMatrix = proj * _viewMatrix;

}

有人可以帮助我了解如何构建视图转换以传递到SpriteBatch中,从而实现所需的功能。

编辑

这似乎是一种转换,但是我不确定为什么。 有人可以帮我分解一下,以了解:

Matrix proj = Matrix.CreateTranslation(new Vector3(_viewport.Width * 0.5f, _viewport.Height * 0.5f, 0));
    _viewMatrix = Matrix.CreateRotationZ(_rotation) *
                 Matrix.CreateScale(new Vector3(_zoom, _zoom, 1.0f)) *
                 Matrix.CreateTranslation(-1 * _position.X, _position.Y, 0.0f);

    _viewMatrix = proj * _viewMatrix;

我之前已经构建了一个raytracer,所以我应该理解您的理解,我的困惑在于它是2D事实,而SpriteBatch向我隐藏了它所做的事情。 谢谢! 法里德

如果使用比例矩阵翻转Y轴上的所有内容,则意味着要翻转SpriteBatch正在绘制的模型(带纹理的四边形)。 这意味着您还必须更改缠绕顺序(即:背面剔除是指您绘制的是面对摄像机的三角形的背面,因此将其剔除,因此必须更改其使用的规则)。

默认情况下, SpriteBatch使用RasterizerState.CullCounterClockwise 调用SpriteBatch.Begin您需要传递RasterizerState.CullClockwise

当然, Begin是您传递转换矩阵的地方。

我没有仔细检查您的矩阵运算-尽管我怀疑顺序不正确。 我建议您创建一个非常简单的测试应用,并一次构建一个转换。

我与XNA进行了很多尝试,试图使其像我以前使用过的其他引擎一样。我的建议, 这是不值得的 。只需遵循XNA标准并使用Matrix helper方法即可。创建您的“透视图/视口”矩阵。

因此,仅需逻辑思考,我就可以推断出正确的变换。 如果有人需要真正的故障,我将在此处概述步骤:

了解什么是相机变换或视图变换很重要。 通常,从对于摄影机的坐标到世界空间坐标,需要进行视图转换。 然后,视图转换的逆过程将使世界相对于您的相机坐标!

创建视图矩阵

  1. 应用相机的旋转。 我们之所以在Z轴上执行此操作仅是因为这是用于2D摄像机的。
  2. 应用相机的变换。 这是有道理的,因为我们想要世界坐标,它是摄影机坐标和相对于摄影机的对象之和。
    1. 您可能会注意到,我将Y分量乘以-1。 这样一来,由于屏幕的Y值指向下方,因此增加“摄像机的Y位置”与向上移动相关。
  3. 应用相机的变焦

现在,矩阵的逆将执行世界坐标->视图坐标。

我还选择将相机居中放置在屏幕中央,因此我添加了一个预先附加的翻译。

Matrix proj = Matrix.CreateTranslation(new Vector3(_viewport.Width * 0.5f, _viewport.Height * 0.5f, 0));

        _viewMatrix = Matrix.CreateRotationZ(moveComponent.Rotation) *
                    Matrix.CreateTranslation(moveComponent.Position.X, -1 * moveComponent.Position.Y, 0.0f) *
                     Matrix.CreateScale(new Vector3(zoomComponent.Zoom, zoomComponent.Zoom, 1.0f));

        _viewMatrix = proj * Matrix.Invert(_viewMatrix);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM