【问题标题】:Improper SpriteBatch RotationSpriteBatch 旋转不当
【发布时间】:2019-04-02 02:13:01
【问题描述】:

我试图让旋转的Texture2D 正确地适合/填充旋转的Polygon(我自己的班级)的范围,但它拒绝正常工作。我使用的SpriteBatch 方法是:

spriteBatch.Draw(texture, new Rectangle((int)Position.X, (int)Position.Y, Width, Height), null, color, Rotation, Vector2.Zero, SpriteEffects.None, 1.0f);

但是,其中唯一重要的位是 Rectangle 和原点,当前设置为 Vector2.Zero。当上面运行时,它会生成this 图像,其中Texture2D(一个实心红色方块)与Polygon(石灰线框)的偏移量为(texture.Width / 2, texture.Height / 2)。但是,旋转是正确的,因为两个形状都有平行的边。

我试过了:

spriteBatch.Draw(texture, new Rectangle((int)Position.X, (int)Position.Y, Width, Height), null, color, Rotation, new Vector2(Width / 2, Height / 2), SpriteEffects.None, 1.0f);

此调用的唯一区别是我将原点(Texture2D应该围绕其旋转的点)更改为new Vector2(Width / 2, Height / 2),从而生成this 图像,其中Texture2DPolygon 的偏移量为 (-Width, -Height),但它仍与 Polygon 一起旋转。

发生的另一个错误是,当使用与第一个具有不同宽度和高度的不同 Texture2D 时 - 尽管它应该产生相同的结果,因为 destinationRectangle 字段不会改变 - 它在程序,如this 图像所示。同样,这使用与上一个完全相同的调用,只是使用不同的图像(具有不同的尺寸)。

我们将不胜感激任何有关这些问题的帮助。谢谢!

【问题讨论】:

    标签: c# xna monogame xna-4.0 spritebatch


    【解决方案1】:

    http://www.monogame.net/documentation/?page=M_Microsoft_Xna_Framework_Graphics_SpriteBatch_Draw

    为了正确旋转,您需要确保origin 正确,

    如果是标准化值,则为 0.5f, 0.5f,否则为 width / 2.0f, height / 2.0f

    或任何其他适合您的情况旋转的角落。

    【讨论】:

      【解决方案2】:

      原点根据源矩形调整旋转中心。 (在您的情况下作为null 传递时,源矩形是整个纹理。

      请记住,在平移、旋转和缩放方面,顺序很重要。

      旋转应用于源矩形的平移原点,允许旋转精灵表的各个帧。

      以下代码应该会产生预期的输出:

      spriteBatch.Draw(texture, new Rectangle((int)Position.Center.X, (int)Position.Center.Y, Width, Height), null, color, Rotation, new Vector2(texture.Width / 2, texture.Height / 2), SpriteEffects.None, 1.0f);
      

      【讨论】:

        【解决方案3】:

        我的两个问题的答案在于一个错误:

        SpriteBatch应用缩放平移之前应用围绕原点的旋转。

        为了解释这一点,这里有一个例子:

        您有一个大小为(16, 16)Texture2D,并希望它在围绕原点(destinationRectangle.Width / 2, destinationRectangle.Height / 2)(等于(24, 24))旋转时填充(48, 48) 大小destinationRectangle。因此,您希望得到一个围绕其中心点旋转的正方形。

        首先,SpriteBatch 将围绕点(24, 24) 旋转Texture2D,因为Texture2D 尚未缩放,因此大小为(16, 16),这将导致不正确和意外的结果。在此之后,它将被缩放,使其只是旋转不佳的正方形的更大版本。

        要解决此问题,请使用 (texture.Width / 2, texture.Height / 2) 而不是 (destinationRectangle.Width / 2, destinationRectangle.Height / 2) 作为起点。

        例如:spriteBatch.Draw(texture, new Rectangle((int)Position.X, (int)Position.Y, Width, Height), null, color, Rotation, new Vector2(texture.Width / 2, texture.Height / 2), SpriteEffects.None, 0f);

        更多解释可以在herehere找到。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-05
          • 2021-04-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多