有没有办法在使用 GLFW 按下一个键后只处理一个输入事件?
Is there a way to process only one input event after a key is pressed using GLFW?
目前,当按住所需的键时,输入会注册多次。有没有办法只处理按下键后的第一个事件,而忽略后面的事件,直到松开键?
我正在使用 processInput 函数,条件如下:
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
currentXPos--;
if (currentXPos < 0)
currentXPos = 0;
}
currentXPos
只是一个受 left/right 箭头键影响的整数。我有一个等效的 currentYPos
整数,它也受 up/down 箭头键的影响。每次按键我需要 increment/decrement currentXPos 一次。我尝试添加一个初始设置为 true 的全局 bool,并在执行时将其设置为 false,如下所示:
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
if (canMove) {
canMove = false;
currentXPos--;
if (currentXPos < 0)
currentXPos = 0;
}
}
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_RELEASE) {
canMove = true;
}
这确实适用于单键,但如果我也使用右箭头键实现此功能(用于递增相同的值),下面的函数会不断地 returns GLFW_RELEASE第一个版本,将 canMove bool 设置为 true 并最终使其冗余;
if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_RELEASE) {
canMove = true;
}
我试过使用 glfwWaitEvents() 但它仍然处理多个输入,帮助超过 0.5 秒左右(与在搜索 bar/text 编辑器中按住键盘上的任何字符的效果相同) .
当你希望每个按键只处理一次时,最好的解决方案是监听按键回调事件,而不是在每一帧中查询按键状态。按键回调是一个可以挂接到 glfw 的函数,每个按键事件都会调用一次。
回调应该看起来像这样:
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_RIGHT && action == GLFW_PRESS)
{
currentXPos--;
if (currentXPos < 0)
currentXPos = 0;
}
}
然后可以在创建 window 之后的某处注册此回调:
glfwSetKeyCallback(window, key_callback);
可以在 GLFW Input Guide 中找到更多详细信息。
目前,当按住所需的键时,输入会注册多次。有没有办法只处理按下键后的第一个事件,而忽略后面的事件,直到松开键?
我正在使用 processInput 函数,条件如下:
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
currentXPos--;
if (currentXPos < 0)
currentXPos = 0;
}
currentXPos
只是一个受 left/right 箭头键影响的整数。我有一个等效的 currentYPos
整数,它也受 up/down 箭头键的影响。每次按键我需要 increment/decrement currentXPos 一次。我尝试添加一个初始设置为 true 的全局 bool,并在执行时将其设置为 false,如下所示:
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
if (canMove) {
canMove = false;
currentXPos--;
if (currentXPos < 0)
currentXPos = 0;
}
}
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_RELEASE) {
canMove = true;
}
这确实适用于单键,但如果我也使用右箭头键实现此功能(用于递增相同的值),下面的函数会不断地 returns GLFW_RELEASE第一个版本,将 canMove bool 设置为 true 并最终使其冗余;
if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_RELEASE) {
canMove = true;
}
我试过使用 glfwWaitEvents() 但它仍然处理多个输入,帮助超过 0.5 秒左右(与在搜索 bar/text 编辑器中按住键盘上的任何字符的效果相同) .
当你希望每个按键只处理一次时,最好的解决方案是监听按键回调事件,而不是在每一帧中查询按键状态。按键回调是一个可以挂接到 glfw 的函数,每个按键事件都会调用一次。
回调应该看起来像这样:
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_RIGHT && action == GLFW_PRESS)
{
currentXPos--;
if (currentXPos < 0)
currentXPos = 0;
}
}
然后可以在创建 window 之后的某处注册此回调:
glfwSetKeyCallback(window, key_callback);
可以在 GLFW Input Guide 中找到更多详细信息。