【发布时间】:2016-09-25 13:55:51
【问题描述】:
所以在过去的一天半里,我一直被这个问题困扰。 我正在尝试在我的 LWJGL 游戏中实现 2D 可写文本框。文本框的渲染没有问题,完美无缺。
但是,我的输入并没有那么好用。问题是我不知道如何检测单次按键,所以没有在我的输入字符串中添加“a”,而是添加:“aaaaaaaaaaaaaaaaaa”,因为游戏时钟非常快。
这是我的代码:
private boolean canType = false;
private static long curTime= System.currentTimeMillis();
private static long keyTypeTime = System.currentTimeMillis();
String input = "";
// Game loop
// I'm using a timer to limit typing, which doesn't work that well.
if (curTime - keyTypeTime >= 100) {
keyTypeTime = System.currentTimeMillis();
canType = true;
}
if (canType) {
char c = Keyboard.checkAllKeys();
canType = false;
if (c != '*') {
if (c == '/') {
System.out.println("backspace");
if (input != null && input.length() > 0) {
input = input.substring(0, input.length() - 1);
}
} else if (c == '{') {
storyLogic();
} else {
input += c;
}
}
}
这是我的实际键盘类,以及“checkAllKeys”方法:
package me.mateo226.main;
导入 org.lwjgl.glfw.GLFWKeyCallback; 导入静态 org.lwjgl.glfw.GLFW.*;
公共类键盘扩展 GLFWKeyCallback{
public static boolean[] keys = new boolean[65536];
// The GLFWKeyCallback class is an abstract method that
// can't be instantiated by itself and must instead be extended
//
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
// TODO Auto-generated method stub
keys[key] = action != GLFW_RELEASE;
}
// boolean method that returns true if a given key
// is pressed.
public static boolean isKeyDown(int keycode) {
return keys[keycode];
}
public static char checkAllKeys() {
char key = '*';
if(isKeyDown(GLFW_KEY_A)) {
key = 'a';
}
if(isKeyDown(GLFW_KEY_Z)) {
key = 'z';
}
if(isKeyDown(GLFW_KEY_SPACE)) {
key = ' ';
}
if(isKeyDown(GLFW_KEY_BACKSPACE)) {
key = '/';
}
if(isKeyDown(GLFW_KEY_ENTER)) {
key = '{';
}
return key;
}
}
我还在学习 LWJGL 3,所以键盘类不是我的,只有 checkAllKeys 方法是我做的。
谢谢!
【问题讨论】: