I rework the code to make it more easier to manage. How can I force the player cannot change the sprite animation by pressing any keys until the attack animation completely ends?
class Player
{
Animation playerIdle;
Animation playerRun;
Animation playerAtk;
public void Load(ContentManager content)
{
playerIdle = new Animation(content, "idle", 144, 128, 8, 30);
playerRun = new Animation(content, "run", 160, 112, 8, 30);
playerAtk = new Animation(content, "atk", 154, 131, 2, 30);
playerIdle.EnableRepeating();
playerRun.EnableRepeating();
playerAtk.EnableRepeating();
}
public void Update(GameTime gameTime)
{
playerIdle.Update(gameTime);
UpdateControl(gameTime);
}
#region Update Control
string selectSpriteSheet;
KeyboardState mPreviousKeyboardState;
SpriteEffects spriteEffects = SpriteEffects.FlipHorizontally;
Vector2 feetPosition = new Vector2(0, 350);
Vector2 mSpeed = Vector2.Zero;
Vector2 mDirection = Vector2.Zero;
Vector2 mStartingPosition = Vector2.Zero;
int CHARACTER_SPEED = 50;
int MOVE_LEFT = -5;
int MOVE_RIGHT = 5;
int MOVE_UP = -5;
int MOVE_DOWN = 5;
enum State
{
Running,
Jumping,
Attacking,
}
State mCurrentState = State.Running;
public void UpdateControl(GameTime gameTime)
{
KeyboardState aCurrentKeyboardState = Keyboard.GetState();
feetPosition += mDirection * mSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
selectSpriteSheet = "idle";
UpdateMovement(aCurrentKeyboardState, gameTime);
//UpdateJump(aCurrentKeyboardState, gameTime);
mPreviousKeyboardState = aCurrentKeyboardState;
}
private void UpdateMovement(KeyboardState aCurrentKeyboardState, GameTime gameTime)
{
if (mCurrentState == State.Running)
{
mSpeed = Vector2.Zero;
mDirection = Vector2.Zero;
if (aCurrentKeyboardState.IsKeyDown(Keys.Left) && !aCurrentKeyboardState.IsKeyDown(Keys.Right))
{
playerRun.Update(gameTime);
selectSpriteSheet = "run";
spriteEffects = SpriteEffects.None;
mSpeed.X = CHARACTER_SPEED;
mDirection.X = MOVE_LEFT;
}
else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) && !aCurrentKeyboardState.IsKeyDown(Keys.Left))
{
playerRun.Update(gameTime);
selectSpriteSheet = "run";
spriteEffects = SpriteEffects.FlipHorizontally;
mSpeed.X = CHARACTER_SPEED;
mDirection.X = MOVE_RIGHT;
}
if (aCurrentKeyboardState.IsKeyDown(Keys.Z) && mPreviousKeyboardState.IsKeyUp(Keys.Z))
{
mCurrentState = State.Attacking;
}
}
if (mCurrentState == State.Attacking)
{
playerAtk.Update(gameTime);
selectSpriteSheet = "hit";
mCurrentState = State.Running;
}
}
#endregion
public void Draw(SpriteBatch spriteBatch)
{
//playerIdle.Draw(spriteBatch, feetPosition, (float)MathHelper.ToRadians(0), 1.0f);
if (selectSpriteSheet == "idle")
playerIdle.Draw(spriteBatch, feetPosition, spriteEffects, (float)MathHelper.ToRadians(0),1.0f);
else if (selectSpriteSheet == "run")
playerRun.Draw(spriteBatch, feetPosition, spriteEffects, (float)MathHelper.ToRadians(0),1.0f);
else if (selectSpriteSheet == "hit")
playerAtk.Draw(spriteBatch, feetPosition, spriteEffects, (float)MathHelper.ToRadians(0), 1.0f);
}
}