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.
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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With