Josh-CO Dev

Solving the worlds problems one line of code at a time.

XNA – Make a sprite face your mouse

Leave a comment

I decided that I wanted to start toying around with an overhead type shooter game and see how hard it would be to roll something out in XNA. As for the basics, I found it to be quite simple and thought I would show it off here. After this guide, you should end up with something like this:

-Start by creating a new project in Visual Studio and name it what you want.
-Download this image and include it in your content project.
-In your game.cs file add these lines of code to the global variables

        Vector2 Position;
        Texture2D Player;
        float angle;

-Position will be the position of your player, Player is your image you just added, and angle will be your angle of rotation.
-Add this to the initialize method:

            Position = new Vector2(150, 150);
            this.IsMouseVisible = true;

-We are defaulting our player position to 150, 150 on the screen and setting our cursor to visible. By default, XNA hides the cursor.
-Now we need to load up our texture. Add this to your loadContent method:

Player = Content.Load("playerOver");

-All this does is loads the image that you just added to your project and sets it to our player texture.
-Now we need to handle getting the angle to the mouse cursor and we also want to let our player move around a bit. Add this to your update method:

            MouseState curMouse = Mouse.GetState();
            Vector2 mouseLoc = new Vector2(curMouse.X, curMouse.Y);

            Vector2 direction = mouseLoc - Position;
            angle = (float)(Math.Atan2(direction.Y, direction.X));

            KeyboardState keyState = Keyboard.GetState();
            if (keyState.IsKeyDown(Keys.A))
                Position.X -= 2;
            if (keyState.IsKeyDown(Keys.D))
                Position.X += 2;
            if (keyState.IsKeyDown(Keys.W))
                Position.Y -= 2;
            if (keyState.IsKeyDown(Keys.S))
                Position.Y += 2;

-This looks more difficult but it is really easy. First we create a new mousestate object so that we can read where our mouse is. Our Vector2 mouseLoc will hold the X,Y coordinates of our mouse. We create a new vector 2 and subtract our sprite’s position from our mouselocation. Honestly, I am not a math wiz. I really don’t fully understand what this is doing but it works. The next line of code creates a new floating point variable and sets our rotation angle by magic! The remainder of the code just reads our keyboard input and will move our sprite 2 pixels in whichever direction using the W,A,S,D keys.
-Finally, we just draw our player to the screen. In your draw method, add this:


            //spriteBatch.Draw(Player, Position, Color.White);
            spriteBatch.Draw(Player, new Rectangle((int)Position.X, (int)Position.Y, Player.Width, Player.Height), null, Color.White, angle, new Vector2(Player.Width / 2, Player.Height / 2), SpriteEffects.None, 0);


-We start by initializing our sprite batch. This is something that is by design and always has to be done before you can call a .draw method. This override of the draw method is a bit complicated so that we can use the angle. What we are doing is first passing in the player texture. This override is actually made for a sprite sheet so we make some minor adjustments. The 2nd parameter is a rectangle that tells us where to draw our texture on the screen. So we create a new rectangle and put it at the player’s X and Y position and set the size to the width and height of the sprite. The null is actually another rectangle that would tell us where to pull the image from the spritesheet if we were using one. Since we have a static texture we set this to null. Color.White is a default and keeps us from tinting our texture. Next we pass in angle and this is what causes our sprite to draw facing the angle of the mouse. Next we need to set the origin point which is the point that the image will revolve around. In the case of a character, this should generally be the middle of the sprite. Next we tell it not to add any sprite effects. Finally, we put a 0 for our layer depth because we are not using any layers!

That’s it! If you run the solution, you should have a player that you can move with the W,A,S,D keys and will face the mouse. I have found that this login only works if you start with the player facing right. This is likely a bug in the logic that I haven’t figured out yet. Also, later on you would want to split all of the player stuff out into it’s own class as eventually you’ll probably have monsters, bullets, etc. There is a lot of room for improvement, but this way is great for learning and grasping the basics.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s