不正确的 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和 origin,当前设置为Vector2.Zero。运行上面的代码时,它会生成图像,其中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),这导致图像中 与Texture2D的偏移Polygon值为(-Width, -Height),但它仍随 旋转Polygon

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

对这些问题中的任何一个的任何帮助将不胜感激。谢谢!


函数式编程
浏览 84回答 3
3回答

胡子哥哥

原点根据源矩形调整旋转中心。(当像null您的情况一样传递时,源矩形是整个纹理。请记住,在涉及平移、旋转和缩放时,顺序很重要。旋转应用于源矩形的平移原点,允许旋转 sprite 表的各个帧。以下代码应产生预期的输出: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);

繁花如伊

http://www.monogame.net/documentation/?page=M_Microsoft_Xna_Framework_Graphics_SpriteBatch_Draw为了正确旋转,你需要确保origin是正确的,0.5f, 0.5f如果它是一个标准化值,要么是,要么是width / 2.0f, height / 2.0f.或者根据您的情况旋转任何其他合适的角。

皈依舞

我的两个问题的答案在于一个错误:SpriteBatch 在应用缩放平移之前应用围绕原点的旋转。为了解释这一点,这里有一个例子:您有一个Texture2D大小为(16, 16),并希望它在围绕原点(等于)旋转时填充一个(48, 48)大小。因此,您希望最终得到一个围绕其中心点旋转的正方形。destinationRectangle(destinationRectangle.Width / 2, destinationRectangle.Height / 2)(24, 24)首先,SpriteBatch将旋转Texture2Daround point (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);可以在此处和此处找到进一步的解释。
打开App,查看更多内容
随时随地看视频慕课网APP