围绕其中心旋转精灵 [英] Rotating a sprite around its center

查看:37
本文介绍了围绕其中心旋转精灵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何使用 Draw 方法中的原点来围绕其中心旋转精灵.我希望有人能解释一下 Draw 方法中 origin 参数的正确用法.

I am trying to figure out how to use the origin in Draw method to rotate a sprite around its center. I was hoping somebody could explain the correct usage of origin parameter in Draw method.

如果我使用以下 Draw 方法(没有指定任何旋转和原点),对象将被绘制在正确/预期的位置:

If I use the following Draw method (without any rotation and origin specified) the the object is drawn at the correct/expected place:

spriteBatch.Draw(myTexture, destinationRectangle, null, Color.White, 0.0f, Vector2.Zero, SpriteEffects.None, 0);

但是,如果我使用如下所示的原点和旋转,对象围绕中心旋转,但对象漂浮在预期位置上方(大约 20 个像素.)

However, if I use the origin and rotation like shown below, the object is rotating around is center but the object is floating above the expecting place (by around 20 pixels.)

Vector2 origin = new Vector2(myTexture.Width / 2 , myTexture.Height / 2 );
spriteBatch.Draw(myTexture, destinationRectangle, null, Color.White, ballRotation, origin, SpriteEffects.None, 0);

即使我将 ballRotation 设置为 0,对象仍然绘制在预期位置上方

Even if I set the ballRotation to 0 the object is still drawn above the expected place

spriteBatch.Draw(myTexture, destinationRectangle, null, Color.White, 0.0f, origin, SpriteEffects.None, 0);

似乎只是通过设置原点,对象的位置会发生变化.

Is seems that just by setting the origin, the placement of the object changes.

谁能告诉我如何正确使用 origin 参数.

Can somebody tell me how to use the origin parameter correctly.

Davor 的回应明确了 origin 的用法.代码中需要进行以下更改才能使其工作:

Davor's response made the usage of origin clear. The following change was required in the code to make it work:

Vector2 origin = new Vector2(myTexture.Width / 2 , myTexture.Height / 2 );
destinationRectangle.X += destinationRectangle.Width/2;
destinationRectangle.Y += destinationRectangle.Height / 2;
spriteBatch.Draw(myTexture, destinationRectangle, null, Color.White, ballRotation, origin, SpriteEffects.None, 0);

推荐答案

这是 origin 的正确用法.但现在你的位置也变成了中心,它不再在左上角,它在中心.它从设置原点之前的位置浮动 width/2height/2 .

this is correct use of origin. but now your position changed also to center, it's not on top left corner anymore, its on center. and it's floating for width/2 and height/2 from position befor seting origin.

因此,如果您的纹理是 20x20,您需要将 X 减去 10(宽度/2)和 Y 减去 10(高度/2),您将获得原始位置.

so if your texture is 20x20, you need to subtract X by 10 (width/2) and Y by 10 (height/2) and you will have original position.

这篇关于围绕其中心旋转精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆