Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating a sprite around its center

Tags:

xna

xna-4.0

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.

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

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

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.

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


Solution:

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);
like image 540
Achint Mehta Avatar asked Jul 18 '13 02:07

Achint Mehta


1 Answers

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.

enter image description here

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.

like image 182
Davor Mlinaric Avatar answered Oct 15 '22 10:10

Davor Mlinaric