如何根据屏幕上下文监听特定的 Java 按键事件?
我正在与其他几个人一起开发一个小型 Java 游戏,但我对关键事件有点困惑。我在网上找到了一个处理 2D 游戏键盘输入的代码片段。我感到困惑的是如何根据你所在的游戏部分来响应某些关键事件。例如,如果你在主菜单,W、A、S 和 D 不应该起作用,但如果你在游戏中,他们应该这样做。
到目前为止,我能想到的唯一解决方案就是使用枚举和开关来确定应该监听哪些键。这可行,但我不确定是否有更好的方法。
如何根据屏幕上下文监听特定的 Java 按键事件?
I'm working on a small Java game with a few other people and I'm a bit stuck with regards to key events. I found a code snippet online that handles keyboard input for a 2D game. What I'm confused about is how to respond to certain key events based on which part of the game you're in. For example, if you're at the main menu, W, A, S, and D shouldn't work, but if you're in the game they should.
The only solution I've been able to come up with so far is just to use an enum and a switch to determine which keys should be listened for. This would work but I'm not sure if there's a better way to do it.
How do I listen for specific Java key events based on screen context?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为每个游戏状态(“主菜单”、“就绪屏幕”、“游戏状态”等)创建一个类将允许您在超类和游戏状态特定侦听器和逻辑中实现通用 KeyListener 样板。
根据记忆,Slick 库 提供了支持此方法的 API。
Creating a class for each game state ('main menu', 'ready screen', 'playing state', etc.) would allow you to implement common KeyListener boilerplate once in a superclass and game state specific listeners and logic.
From memory the Slick library provides an API supporting this approach.