gpt4 book ai didi

java - LWJGL 键盘循环

转载 作者:行者123 更新时间:2023-12-01 23:27:09 24 4
gpt4 key购买 nike

我创建了一个静态输入类,它基本上有一个我可以调用的方法,如下:

public static boolean GetKeyDown(int keyCode) {
while(Keyboard.next()) {
Keyboard.enableRepeatEvents(false);
if (Keyboard.getEventKeyState()) {
if (Keyboard.getEventKey() == keyCode) {
return true;
} else {
return false;
}
}
}
return false;
}

在我的游戏更新循环中,我想使用它,而不是必须创建一个 while 循环:

if(Input.GetKeyDown(KeyCode.S)) {
//Something happens
}
if(Input.GetKeyDown(KeyCode.R)) {
//Something happens
}
//etc..

但似乎只有第一个加载的才能工作。在本例中为“S”。有没有办法让我也能够使用其他人?

最佳答案

这是因为在您的 GetKeyDown() 方法中,您调用 Keyboard.next(),当您调用该方法时,它会删除 Event > 来自 Keyboard 的当前键,当您调用 Display.update();

时,唯一会用事件重新填充

NOTE: This method does not query the operating system for new events. To do that, Display.processMessages() (or Display.update()) must be called first.

来源:LWJGL Docs

你可以

您可以使用 Keyboard.isKeyDown(int key)方法,以实现您想要做的事情。

虽然它返回 true/false 取决于以下内容。

Returns: true if the key is down according to the last poll()

但这仍然不能完全解决问题,因为它依赖于 poll() 方法。

解决问题

您可以通过创建一些与 Keyboard 类一起使用的自定义方法来解决问题,正如您已经所做的那样,尽管如上所述,键盘事件仅在您调用 Display 时才会更新。 update(); 方法。

您已经对要创建哪个函数有了正确的想法,尽管您需要将它们分成两种不同的方法。您需要一个辅助方法,每次您想要更新键盘时调用一次。

public class MyKeyboard {
/*
* Remember that the index where we store the value,
* is the index of the key. Thereby one key might have
* an index of 400, then your array need to have at least
* the same size, to be able to store it.
*/
public static boolean[] keys = new boolean[100]; // 100 is the amount of keys to remember!

public static void update() {
while(Keyboard.next()) {
if (Keyboard.getEventKey() < keys.length) {
keys[Keyboard.getEventKey()] = Keyboard.getEventKeyState();
}
}
}

public static boolean isKeyDown(int key) {
if ((key > 0) && (key < keys.length)) {
return keys[key];
}

return false;
}
}

记住每次 Display.update() 只调用一次 MyKeyboard.update() 方法,我还重命名了您的 GetKeyDown() 方法到 isKeyDown()因为我认为这听起来和描述它更好,但如果您愿意,您可以在项目中再次重命名它。

上面的代码是在这个答案中编写的,没有使用 IDE 等。因此,如果有任何问题,我深表歉意,但只需发表评论,我会修复它。

这种方法出现的一个问题是缺乏重新检查。由于 Keyboard.next() 仅检查当前帧中发生的输入。曾经按下过的按钮将保持“按下”状态,直到再次按下。我在尝试实现此解决方案时遇到了这个问题。这个新问题的答案在这里:

public static void update() {

for(int i = 0; i < keys.length; i++) {
keys[i] = false;
}
while(Keyboard.next()) {
keys[Keyboard.getEventKey()] = Keyboard.getEventKeyState();
}
}

您必须通过将所有内容设置为 false 来清除前一帧的按键。

关于java - LWJGL 键盘循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19820251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com