SpriteBatch旋转不正确

时间:2019-04-02 02:13:02

标签: c# xna monogame xna-4.0 spritebatch

我正在尝试使旋转的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(石灰线框)的偏移量为{{1} }。但是,旋转是正确的,因为两种形状都具有平行边。

我尝试过:

(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,结果为{{3 }}图像,其中new Vector2(Width / 2, Height / 2)Texture2D的偏移量为Polygon,但它仍与(-Width, -Height)一起旋转。

发生的另一个错误是,当使用与第一个宽度和高度不同的其他Polygon时,尽管Texture2D字段不变,但它会产生相同的结果,在程序中有所不同,如this图像所示。同样,它使用与前一个完全相同的调用,只是具有不同的图像(具有不同的尺寸)。

在这些问题上的任何帮助将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:0)

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

为正确旋转,您需要确保origin是正确的,

如果是归一化值,则为0.5f, 0.5f,否则为width / 2.0f, height / 2.0f

或任何其他合适的角落可以旋转。

答案 1 :(得分:0)

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

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

要说明这一点,下面是一个示例:

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

首先,SpriteBatch将使Texture2D绕点(24, 24)旋转,因为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中找到。

答案 2 :(得分:0)

原点根据源矩形调整旋转中心。 (按照您的情况作为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);
相关问题