How do I handle simultaneous key presses in Java?(如何在 Java 中处理同时按键?)
问题描述
如何在 Java 中处理同时按下的按键?
How do I handle simultaneous key presses in Java?
我正在尝试编写游戏,需要同时处理多个按键.
I'm trying to write a game and need to handle multiple keys presses at once.
当我按住一个键(例如向前移动)然后按住另一个键(例如向左转)时,会检测到新键,但不再检测到旧按键.
When I'm holding a key (let's say to move forward) and then I hold another key (for example, to turn left), the new key is detected but the old pressed key isn't being detected anymore.
推荐答案
一种方法是跟踪自己当前关闭的键.
One way would be to keep track yourself of what keys are currently down.
当你得到一个 keyPressed 事件时,将新的键添加到列表中;当您收到 keyReleased 事件时,从列表中删除该键.
When you get a keyPressed event, add the new key to the list; when you get a keyReleased event, remove the key from the list.
然后在您的游戏循环中,您可以根据键列表中的内容执行操作.
Then in your game loop, you can do actions based on what's in the list of keys.
这篇关于如何在 Java 中处理同时按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中处理同时按键?
基础教程推荐
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- JPA惰性列表上的流 2022-01-01
