繁体   English   中英

使用 GLFW3 在 emscripten 中实现 KeyJustDown

[英]KeyJustDown implementation in emscripten using GLFW3

我想实现KeyJustDown function 来检查给定的键是否被按下。 键刚被按下,如果在当前state是down,而在之前的state是up。

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

在帧的开头,我还像这样更新输入 state:

struct InputState {
    char keysPrev[256];
    char keysCurr[256];
} inputState;

void updateInput() {
    memcpy(inputState.keysPrev, inputState.keysCurr, 256);

    glfwPollEvents();
}

这适用于桌面上的 glfw3 应用程序。 调用glfwPollEvents function 时会调度回调。 但是,这在使用 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 E\n");
    }

    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在 emscripten 实现中什么都不做。 实际的事件回调可以随时发生。 为了解决我的问题,我在检查输入后移动了updateInput function :

void update() {
    if (isKeyJustDown(GLFW_KEY_E)) {
        printf("Key E\n");
    }

    glfwSwapBuffers(window);
    updateInput();
}

相关链接:

https://github.com/raysan5/raylib/pull/2380

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM