# Monogame - Sprite sheet animation

I have a sprite sheet that contains a character walk cycle, and I have made a player class that allows the player to move and cycle through the walk animation, however the animation only works whilst walking to the right. I use the arrow keys to move up, down, left and right, meaning when I press any key, my player moves in the correct direction, but only performs the animation of walking to the right.

The current animation that works, has been called like this in the LoadContent() function:

spritesheet = Content.Load<Texture2D>("sprites2");

player = new Player(spritesheet, new Rectangle(0, 96, 32, 48),
new Vector2(100, 100), 4);


This does its job, as it calls each 4 sprites to complete the walking animation to the right, and new Rectangle(0,96,32,48) is the location cut out from the sprite sheet. However I need (for example) new Rectangle(30, 101, 65, 52) to be used also, which will correctly animate my character when the left arrow key has been pressed.

My question is, how would I get another location of the sprite sheet loaded, and then actually work when I press the correct key?

This is a very difficult question to ask and I very much apologize if it was difficult to understand. Accepting all edits to my question, and thank you in advanced.

A very high-level thought would be to separate your sprite-sheet into different sheets for each direction so that on different key-presses you can specify which sheet to cycle through, and then you don't need to worry about confusing offsets

• This is a very inefficient solution. What if you want the character to do a jumping animation? Soon you'll end up with tons of animation sheets for a single character- basically removing the reason to have a spritesheet in the first place. – Felsir Dec 2 '16 at 15:08

Store your animations in an animation dictionary. You can use a Dictionary<string,Rectangle[]> or create a more elaborate construction that holds more frame information (rectangle, timing, offsets).

So you have a dictionary like this (all pseudo code):

Animations["walk_right"]=new Rectangle[4]{new Rectangle(0,0,10,10), ... }


Keep in your character object the current animation and the timing.

 if(walking_to_right)
current_animation="walk_right";
if(walking_to_left)
current_animation="walk_left";

//-- do the timing stuff


then in the draw:

 spriteBatch.Draw(spritesheet,position,animation[current_animation][frame]);


A possible approach would be to have one animation per row, and then the desired row could be passed in based on the direction.