I am new here and not quite the best when it comes to coding. (using monogame variation of XNA for this) I have successfully recreated a class to animate my sprite sheet i have made but the problem I have encountered is that soon as I tried to implement key presses along with animations, the animation stops moving (stuck on the first frame)
my update class which looks like this
previousKBState = currentKBState;
currentKBState = Keyboard.GetState();
if (previousKBState.IsKeyDown(Keys.D))
{
playerSprite.LoadGraphic(Content.Load<Texture2D>("Sprites\\walk_right.png"), 5, 15, 672, 631, 30);
}
else if (previousKBState.IsKeyDown(Keys.A))
{
playerSprite.LoadGraphic(Content.Load<Texture2D>("Sprites\\walk_left.png"), 5, 15, 672, 631, 30);
}
else
{
playerSprite.LoadGraphic(Content.Load<Texture2D>("Sprites\\idle_right.png"), 5, 10, 610, 423, 5);
}
and this is my LoadGraphic class
public void LoadGraphic(Texture2D texture, int rows, int columns, int width, int height, int animationSpeed)
{
this.Texture = texture;
this.rows = rows;
this.columns = columns;
this.width = width;
this.height = height;
this.animationSpeed = (float)1 / animationSpeed;
totalElapsed = 0;
currentRow = 0;
currentColumn = 0;
}
my Draw Class
public void Draw(SpriteBatch spriteBatch, Vector2 position, Color color)
{
spriteBatch.Draw(Texture,
new Rectangle((int)position.X, (int)position.Y, width, height),
new Rectangle(currentColumn * width, currentRow * height, width, height), color);
}
so the problem I think I am running into is that when I hold the D or A key down, the line of code LoadGraphics keeps on refreshing the call to the other class before the animation can play out.
It would help out if anyone could give me any suggestions how to fix this Thank you
You are right, you are resetting all values to 0 while key is being held down by calling LoadGraphic
each frame. You need to check if correct animation is already playing and do nothing in that case.
Also, I would avoid calling Content.Load<Texture2D>()
from your update code. I would load all textures inside LoadContent()
method and then use them when necessary.