不正确的SpriteBatch旋转

问题描述 投票:0回答:3

我试图让旋转的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
3个回答
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

或者在你的情况下旋转的任何其他适当的角落。


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);

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

© www.soinside.com 2019 - 2024. All rights reserved.