c# - 箭头键导致 WPF 游戏出现巨大延迟
问题描述
我在 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# 项目,所以我可能把很多事情都复杂化了!
解决方案
e.Handled = true
在所有情况下设置。
箭头键在 WPF 框架中具有功能(定位、调整大小)。如果您指出您的用户代码已经处理了它们,它们将不再被转发到窗口框架,这显然需要花费时间来处理它们。
OnPreviewKeyDown
另一种选择是在事件管道中更早地捕获击键,方法是仅针对您不处理的击键覆盖和调用其基数。
推荐阅读
- css - Selenium findElement(By.cssSelector) 用于没有关联标签的“文本”
- r - 为每个组中的最新日期创建新的列指示器
- python - 是否有关于肘部方法中 k 值的最佳范围的研究?
- sequelize.js - Sequelize CLI:sequelize init:models,这是如何工作的?
- linux - 跟踪 Linux 进程的页表访问
- mysql - 从 phpmyadmin 4.9.2 删除数据库并且它仍然连接
- python - Python WebScraping with Selenium&gChrome
- javascript - req.headers['authorization'] 在 Nodejs JWT(JSON WEB TOKEN)中未定义
- github - Azure DevOps Pipeline 无法读取 github 的用户名
- angular - Angular:数据详细信息页面未随新产品更新