Rotating a sprite around its center
Asked Answered
W

1

9

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);
Whitley answered 18/7, 2013 at 2:30 Comment(0)
P
12

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.

Poisson answered 18/7, 2013 at 7:2 Comment(2)
This makes sense. So it seems that the position we are specifying in draw method is for the origin and not for the starting position of object.Whitley
Don't you mean Y by 10 (height/2)?Rivera

© 2022 - 2024 — McMap. All rights reserved.