如何使用GLFW制作事件输入系统?

问题描述 投票:0回答:1

我正在尝试用 OpenGL 和 GLFW 制作一个小游戏引擎。我尝试让输入发挥作用,他们做到了!但它非常笨重,因为您需要对 window 对象的引用,这意味着处理来自 main.cpp 之外的脚本的输入并不方便。

#include<iostream>
#include "inputHeader.h"
#include <GLFW/glfw3.h>

bool GetKey(GLFWwindow* window, int KeyCode)
{
    if (glfwGetKey(window, KeyCode) == GLFW_PRESS)
        return true;
    else
        return false;
}

bool GetKeyDown(GLFWwindow* window, int key) {
    static bool keyPreviouslyPressed[GLFW_KEY_LAST + 1] = { false }; 

    if (glfwGetKey(window, key) == GLFW_PRESS && !keyPreviouslyPressed[key]) {
        keyPreviouslyPressed[key] = true;
        return true;
    }

    return false;
}

//input activation from main.cpp

if (GetKey(window, GLFW_KEY_SPACE))
{
    //do stuff
}

如何才能使您不需要引用窗口对象来处理输入?

c++ events input glfw
1个回答
0
投票

好吧,您可以研究行为设计模式 [1],在您的情况下,我相信观察者模式就足够了。幸运的是,您的提示与这篇文章相似[2]使用提供一些事件处理机制的回调。

GLFWkeyfun glfwSetKeyCallback (GLFWwindow * window, GLFWkeyfun  callback)

  1. https://refactoring.guru/design-patterns/behavioral-patterns
  2. 如何针对不同的类进行glfwSetKeyCallback?
  3. https://www.glfw.org/docs/3.3/group__input.html#ga1caf18159767e761185e49a3be019f8d
© www.soinside.com 2019 - 2024. All rights reserved.