Export (0) Print
Expand All

How To: Rotate a Sprite

This article demonstrates how to rotate a sprite around its center.

The source code in this example presumes that the texture being loaded is 64×64 pixels.

The Complete Sample

The code in this tutorial illustrates the technique described in the text. A complete code sample for this tutorial is available for you to download, including full source code and any additional supporting files required by the sample.

To draw a rotated sprite on screen

  1. Follow steps 1–4 of How To: Draw a Sprite.
  2. Determine the screen location of the sprite, and the point within the texture that will serve as the origin. By default, the origin of a texture is (0,0), the upper-left corner. When a sprite is drawn, the origin point in the texture is placed on the screen coordinate specified by the at parameter. In this example, the origin is the center of the texture, and the screen position is the center of the screen.

    private Texture2D SpriteTexture;
    private Vector2 origin;
    private Vector2 screenpos;
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
        SpriteTexture = Content.Load<Texture2D>("ship");
        Viewport viewport = graphics.GraphicsDevice.Viewport;
        origin.X = SpriteTexture.Width / 2;
        origin.Y = SpriteTexture.Height / 2;
        screenpos.X = viewport.Width / 2;
        screenpos.Y = viewport.Height / 2;
    }
    
  3. In your Update method, determine the rotation angle to use for the sprite. The angle is specified in radians, and it can be greater than two times pi, but does not need to be.

    private float RotationAngle = 0f;
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();
    
        // The time since Update was called last.
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
    
        // TODO: Add your game logic here.
        RotationAngle += elapsed;
        float circle = MathHelper.Pi * 2;
        RotationAngle = RotationAngle % circle;
    
        base.Update(gameTime);
    }
    
  4. In your own Draw method, call SpriteBatch.Draw with the texture, angle, screen position, and origin of the texture.

    protected override void Draw(GameTime gameTime)
    {
        graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
    
        // TODO: Add your drawing code here
        spriteBatch.Begin();
        spriteBatch.Draw(SpriteTexture, screenpos, null, Color.White, RotationAngle,
            origin, 1.0f, SpriteEffects.None, 0f);
        spriteBatch.End();
    
        base.Draw(gameTime);
    }
    
  5. When all the sprites have been drawn, call End on your SpriteBatch object.

Community Additions

ADD
Show:
© 2014 Microsoft