I've made a snake game in WPF which works perfectly using WASD, but when I use the arrow keys instead, using the exact same code, it lags for 5 seconds after each key press.
A feature of the game is that you can adjust the play area size. When the play area size is small, the delay is short to non-existant. When the play area size is large, the delay is much more noticable. I do not however think the issue is with the game size, as it works fine with WASD.
The code I use to capture key input is below:
private void Window_KeyDown(object sender, KeyEventArgs e) { // Window_KeyDown is called every time the user presses a key. If the key is one of W, A, S, D, Up, Down, Left, Right (movement direction) or Space (play/pause), it will call the relevant functions.
if (gameStateBools.isInGame && !gameStateBools.isPaused) {
switch (e.Key) {
case (Key.Space): // Space "Clicks" the playPauseButton.
playPauseButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
break;
case (Key.W): // W changes the pendingDirection to move up.
if (gameState.direction != 1) {
pending.pendingDirection = 0;
ArrowFromDirection();
}
break;
case (Key.S): // S changes the pendingDirection to move down.
if (gameState.direction != 0) {
pending.pendingDirection = 1;
ArrowFromDirection();
}
break;
case (Key.A): // A changes the pendingDirection to move left.
if (gameState.direction != 3) {
pending.pendingDirection = 2;
ArrowFromDirection();
}
break;
case (Key.D): // D changes the pendingDirection to move right.
if (gameState.direction != 2) {
pending.pendingDirection = 3;
ArrowFromDirection();
}
break;
case (Key.Up): // Up changes the pendingDirection to move up.
if (gameState.direction != 1) {
pending.pendingDirection = 0;
ArrowFromDirection();
}
break;
case (Key.Down): // Down changes the pendingDirection to move down.
if (gameState.direction != 0) {
pending.pendingDirection = 1;
ArrowFromDirection();
}
break;
case (Key.Left): // Left changes the pendingDirection to move left.
if (gameState.direction != 3) {
pending.pendingDirection = 2;
ArrowFromDirection();
}
break;
case (Key.Right): // Right changes the pendingDirection to move right.
if (gameState.direction != 2) {
pending.pendingDirection = 3;
ArrowFromDirection();
}
break;
}
}
}
EDIT: I've open sourced the project now that it's fixed :) https://github.com/jacobcxdev/UTC-Snake. Please note that this is my first C# project, so I've probably overcomplicated many things!