Search code examples
c++eventsinputglfw

How do I make an event input system with GLFW?


I am trying to make a little game engine with OpenGL and GLFW. I've tried to get inputs to work and they do! But it's very clunky because you need a reference to the window object meaning it's not convenient to handle inputs from scripts other than 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
}

How can I make it so that you don't need a reference to the window object to handle input?


Solution

  • Well you can look into Behavioral Design Patterns [1] in your case I believe the observer pattern would be sufficient. Luckily your prompt, is similar to this post [2] using callbacks providing some event handling mechanisms.

    GLFWkeyfun glfwSetKeyCallback (GLFWwindow * window, GLFWkeyfun callback)

    1. https://refactoring.guru/design-patterns/behavioral-patterns
    2. How to glfwSetKeyCallback for different classes?
    3. https://www.glfw.org/docs/3.3/group__input.html#ga1caf18159767e761185e49a3be019f8d