Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monogame rotating a sprite

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);
like image 281
Darkbound Avatar asked Dec 11 '22 22:12

Darkbound


1 Answers

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.

like image 126
craftworkgames Avatar answered Dec 25 '22 20:12

craftworkgames