簡體   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