KeyJustDown的实现使用GLFW3



我想实现KeyJustDown函数检查,如果给定的键刚刚按下。如果当前状态下的键是下的,上一状态下的键是上的

int isKeyJustDown(int key) {
return !inputState.keysPrev[key] && inputState.keysCurr[key];
}

在帧的开始我也更新输入状态,像这样:

struct InputState {
char keysPrev[256];
char keysCurr[256];
} inputState;
void updateInput() {
memcpy(inputState.keysPrev, inputState.keysCurr, 256);
glfwPollEvents();
}

这在桌面的glfw3应用程序中工作得很好。当glfwPollEvents函数被调用时,回调函数被调度。但是,当使用emscripten时,这并不适用。

我有两个问题当使用emscripten时,回调到底在什么时候被调度(它们是在事件发生时立即发生还是在循环中有某个特定的点发生)?当使用emscripten时,我如何实现与桌面相同的行为?

下面是完整的例子:

#include <GLFW/glfw3.h>
#include <memory.h>
#include <stdio.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
GLFWwindow *window;
struct InputState {
char keysPrev[256];
char keysCurr[256];
} inputState;
void updateInput() {
memcpy(inputState.keysPrev, inputState.keysCurr, 256);
glfwPollEvents();
}
int isKeyJustDown(int key) {
return !inputState.keysPrev[key] && inputState.keysCurr[key];
}
void update() {
updateInput();
if (isKeyJustDown(GLFW_KEY_E)) {
printf("Key En");
}
glfwSwapBuffers(window);
}
void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) {
if (key < 0) return;
inputState.keysCurr[key] = action != GLFW_RELEASE;
}
int main() {
if (!glfwInit()) return 1;
window = glfwCreateWindow(1280, 720, "Input test", NULL, NULL);
if (!window) return 1;
glfwSetKeyCallback(window, keyCallback);
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(update, 0, 1);
#else
while (!glfwWindowShouldClose(window)) {
update();
}
glfwTerminate();
#endif
return 0;
}

看起来glfwPollInput在脚本实现中什么都不做。实际的事件回调可以在任何时候发生。为了解决我的问题,我在检查输入后移动了updateInput函数:

void update() {
if (isKeyJustDown(GLFW_KEY_E)) {
printf("Key En");
}
glfwSwapBuffers(window);
updateInput();
}

相关链接:https://github.com/raysan5/raylib/pull/2380

https://github.com/raysan5/raylib/issues/2379

最新更新