我已经在WPF中制作了一个蛇形游戏,可以在WASD上完美运行,但是当我使用箭头键代替时,使用完全相同的代码,每次按下键后滞后5秒钟。
游戏的一个特点是您可以调整游戏区域的大小。当游乐区尺寸较小时,延迟很短甚至不存在。当游戏区域较大时,延迟会更加明显。但是我认为问题不在于游戏大小,因为它在WASD上可以正常工作。
我用来捕获按键输入的代码如下:
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;
}
}
}
编辑:我已经开源了该项目,因为它是固定的:) https://github.com/jacobcxdev/UTC-Snake。请注意,这是我的第一个C#项目,所以我可能使很多事情变得过于复杂了!
答案 0 :(得分:1)
在所有情况下都设置e.Handled = true
。
箭头键在WPF框架中具有一个功能(定位,调整大小)。如果您指示用户代码已处理它们,则它们将不再转发到窗口框架,这显然需要花费时间来处理这些窗口。
另一种选择是通过覆盖OnPreviewKeyDown
并在事件管道中更早地捕获击键,并仅将其作为您未处理的击键的基础。