I am trying to rotate a sprite in Monogame, but for some reason I can't get it right! I would be really grateful if someone explains the mystery of rotation!
This is the line of code that I am using to draw and rotate my sprite, just a note the variable rotation
is the angle I am incrementing it by 0.1 on every Update, this is just for testing purpose. How do I make the cannon rotate around an origin point that is inside the image? For example around its center point like a helicopter propeller? Check the video to see the result from this line of code.
spriteBatch.Draw(cannon.image, new Rectangle(300, 300, cannon.image.Width, cannon.image.Height), null, Color.White, rotation, new Vector2(0, 0), SpriteEffects.None, 0f);
This looks like the overload you're using:
public void Draw (
Texture2D texture,
Vector2 position,
Nullable<Rectangle> sourceRectangle,
Color color,
float rotation,
Vector2 origin,
float scale,
SpriteEffects effects,
float layerDepth
)
The problem is that you need to set the origin point to rotate around. In MonoGame / XNA the origin is specified in pixels relative to the size of the texture. So to calculate the centre of the sprite you need to do something like this:
var origin = new Vector2(texture.Width / 2f, texture.Height / 2f);
Then call the sprite batch draw method like so:
spriteBatch.Draw(cannon.image, new Rectangle(300, 300, cannon.image.Width, cannon.image.Height), null, Color.White, y, origin, SpriteEffects.None, 0f);
Lastly, please don't use y
as the variable name for rotation, it could be very confusing for another programmer reading your code. A better name would be rotation
.
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