Skip to content

XNA RotatingaSprite

Simon (darkside) Jackson edited this page Aug 21, 2020 · 2 revisions

XNA - Rotating a Sprite

*Note, this article references XNA V1 - MonoGame update to follow

Spinning a sprite in XNA is alot easier than it ever has been :)

Lots of assemblies as usual

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

Lets dig into some useful code.. :)

namespace SimpleXNA
{
     public class Game1 : Microsoft.Xna.Framework.Game
    {

I have modified this sample to render a rotating picture inside the window so lets add the following code right here:

        SpriteBatch spriteBatch;
        Texture2D pTex;
        float fRot = 0.0f;   // this will hold the rotation of the sprite

I have also created a function for loading a texture:

        public Texture2D LoadTexture(string strPath)
        {
            TextureInformation information = Texture.GetTextureInformation(strPath);
            //Not in the cache - need to read it in
            IGraphicsDeviceService graphicsService = (IGraphicsDeviceService)
                GameServices.GetService(typeof(IGraphicsDeviceService));

            Texture2D tex = Texture2D.FromFile(
                       graphicsService.GraphicsDevice, 
                       strPath, information.Width, information.Height);

            return tex;
        }

You should hook into the Exiting event so you can clean up any resources you create. This can be done by viewing the Game1.Designer.cs file

In this method i added the code for hooking into the Starting and Exiting events:

private void InitializeComponent()
{

    this.graphics = new Microsoft.Xna.Framework.Components.GraphicsComponent();

    this.Starting += new 
              System.EventHandler<Microsoft.Xna.Framework.GameEventArgs>
                     (this.WindowsGame_Starting);
    this.Exiting += new 
               System.EventHandler<Microsoft.Xna.Framework.GameEventArgs>
                     (this.WindowsGame_Exiting);

    this.GameComponents.Add(this.graphics);
}

Back in the Game1.cs file we create the Exiting and Starting methods:

We should clean up the resources we create upon exiting :)

        private void WindowsGame_Exiting(object sender, GameEventArgs e)
        {
            spriteBatch.Dispose();
            pTex.Dispose();

        }

When the game loads, lets create a texture and resize the window to fit the size of the texture

        private void WindowsGame_Starting(object sender, GameEventArgs e)
        {

            pTex = LoadTexture(@"spiral.jpg");

            graphics.BackBufferFormat = SurfaceFormat.Color;

            graphics.BackBufferWidth = 800;
            graphics.BackBufferHeight = 600;

            graphics.IsFullScreen = false;

            graphics.SynchronizeWithVerticalRetrace = false;

            graphics.AllowMultiSampling = true;

            graphics.ApplyChanges();


            spriteBatch = new SpriteBatch(graphics.GraphicsDevice);

        }

I did not modify the Game1 constructor code

        public Game1()
        {
            InitializeComponent();
        }

This update function was generated by the App Wizard.

This is where you would place any logic that should be handled each frame of the games rendering:

        protected override void Update()
        {
            // The time since Update was called last
            float elapsed = (float)ElapsedTime.TotalSeconds;

            // TODO: Add your game logic here

            // Let the GameComponents update
            UpdateComponents();
        }

the Draw() method is the perfect place to render to the scree :)

I have added the spriteBatch.Draw to render the image in side the game window:

        protected override void Draw(GameTime gameTime)
        {
           GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

Lets increment the rotation counter

Update the rotation based on the elapsed time

            float fRot = (float)gameTime.TotalTime.TotalSeconds;

Now we draw the sprite giving it the rotation we want:

            spriteBatch.Draw(pTex, 
                 
                 //this is the destination point we want to render at
                 new Vector2(this.Window.ClientWidth/2,   
                                    this.Window.ClientHeight/2),

                //this is the texture surface area we want to use when rendering
                new Rectangle(0,0,pTex.Width,pTex.Height),
                
                //By using White we are basically saying just use the texture color
                Color.White, 

                //Here is the rotation in radians
                fRot, 

                //This is the center point of the rotation
                new Vector2(pTex.Width/2, pTex.Height/2),

                //This is the scaling of the sprite. I want it a bit larger so you dont
                //see the edges as it spins around
                1.5f,
                 
                //We are not doing any fancy effects
                SpriteEffects.None,0);

            spriteBatch.End();
            

            base.Draw(gameTime);
        }

    }
}
Clone this wiki locally