I have a top-down game that has 8 directions of movement (top/down/left/right/topright/topleft/bottomright/bottomleft). There are sprites for each direction of movement. This is just an example spritesheet:
The problem is when I want to retain the vertical position. When I let go of the buttons on the keyboard, it polls the keys quickly and ends up facing the character in either left/right/up/down position depending on the last key that was released.
I added a delay for polling the keypresses, but I do not like this solution as it creates a noticeable lag.
Can anyone think of logic that would be able to allow my sprite to retain the proper direction when the keys are unpressed? Here is the current code:
if (kbState.IsKeyDown(Keys.Up) && kbState.IsKeyDown(Keys.Left))
character.ChangeDirection(Direction.UpLeft);
else if (kbState.IsKeyDown(Keys.Up) && kbState.IsKeyDown(Keys.Right))
character.ChangeDirection(Direction.UpRight);
else if (kbState.IsKeyDown(Keys.Down) && kbState.IsKeyDown(Keys.Left))
character.ChangeDirection(Direction.DownLeft);
else if (kbState.IsKeyDown(Keys.Down) && kbState.IsKeyDown(Keys.Right))
character.ChangeDirection(Direction.DownRight);
else if (kbState.IsKeyDown(Keys.Up))
character.ChangeDirection(Direction.Up);
else if (kbState.IsKeyDown(Keys.Down))
character.ChangeDirection(Direction.Down);
else if (kbState.IsKeyDown(Keys.Left))
character.ChangeDirection(Direction.Left);
else if (kbState.IsKeyDown(Keys.Right))
character.ChangeDirection(Direction.Right);
Edit
Settled for the following code:
float delay = 0.04f;
float DELAY = 0.04f;
....
//Get movement
delay -= (float)gameTime.ElapsedGameTime.TotalSeconds;
if (delay < 0)
{
int vertical = kbState.IsKeyDown(Keys.Up) ? -1 : kbState.IsKeyDown(Keys.Down) ? 1 : 0;
int horizontal = kbState.IsKeyDown(Keys.Left) ? -1 : kbState.IsKeyDown(Keys.Right) ? 1 : 0;
movement = new Vector2(horizontal, vertical);
delay = DELAY;
}
character.Update(gameTime, movement);
Seems I have to use a delay in order to get this to work. Thanks for the feedback guys.