4

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);
SuperJMN
  • 13,110
  • 16
  • 86
  • 185
Darkbound
  • 3,026
  • 7
  • 34
  • 72

2 Answers2

15

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.

craftworkgames
  • 9,437
  • 4
  • 41
  • 52
  • Thanks, this was the problem indeed, I wasn't setting the correct origin point. As far as the y variable, it was just for testing purposes. :) – Darkbound Jun 30 '15 at 15:09
  • No problem. I'm glad you sorted it out yourself. I thought it was worth explaining the details. Please mark the answer as accepted. Cheers – craftworkgames Jul 01 '15 at 00:14
0

Answer: in the new Vector2(x, y) I just had to set x and y values that are within the image.

Darkbound
  • 3,026
  • 7
  • 34
  • 72
  • 2
    You should mark the answer of @craftworkgames as the accepted answer and not mention it as your own answer and accept it! – Syed Waqas Aug 21 '17 at 10:07