如何在GLFW中为游戏引擎做适当的输入类

时间:2019-04-08 12:13:47

标签: c++ opengl input game-engine glfw

我正在做一个我的小项目,基本上是在创建自己的c ++游戏引擎/框架来创建图形和/或简单游戏。我将OpenGL与GLFW一起使用。我的目标是要拥有与各种图形框架类似的东西,例如raylib或openFrameworks(当然要精简一下)

到目前为止,实际上一切正常,但是我不知道如何正确地将输入与窗口类分开,因为对我而言,拥有窗口句柄输入似乎很笨拙,只会使窗口类混乱。

这是对我的窗口类的快速简化。 (我没有将enum类包含在键码中。)

#pragma once
#include "../extern/GLFW/glfw3.h"
#include <string>
class Window {
private:
    GLFWwindow* mWindow;
    int mWidth;
    int mHeight;
    std::string mTitle;

public:
    Window();
    ~Window();

    void createWindow(std::string title, int width, int height);
    void mainLoop();

    GLFWwindow* getWindow() const { return mWindow; }


// Input
private:

    bool Window::getKeyStatus(KEY key) {
    static void keyCallback(GLFWwindow* mWindow, int key, int scancode, int action, int mods);
    bool isKeyDown(KEY key);
};

这是实现加上

#include "Window.h"
#include <iostream>

Window::Window() {}
Window::~Window() {}

void Window::createWindow(std::string title, int width, int height) {
    if (!glfwInit());
    mWindow = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr);

    if (!getWindow()) {
        glfwTerminate();
    }


    glfwSetWindowUserPointer(getWindow(), this);
    glfwMakeContextCurrent(getWindow());


    glfwSetKeyCallback(mWindow, keyCallback);
}

void Window::mainLoop() {
    while (!glfwWindowShouldClose(getWindow())) {
        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        /* Swap front and back buffers */
        glfwSwapBuffers(getWindow());

        /* Poll for and process events */
        glfwPollEvents();


        if (isKeyDown(KEY::A)) {
            std::cout << "A down" << std::endl;
        }
        if (isKeyDown(KEY::B)) {
            std::cout << "B down" << std::endl;
        }

    }

    glfwTerminate();
}

void Window::keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
    Window* win = (Window*)glfwGetWindowUserPointer(window);

    if (key == (int)KEY::ESCAPE && action == GLFW_PRESS) {
        glfwSetWindowShouldClose(window, GL_TRUE);
    } else {
        win->currentKeyState[key] = action;
    }
}

bool Window::getKeyStatus(KEY key) {
    return glfwGetKey(mWindow, (int)key);
}
bool Window::isKeyDown(KEY key) {
    bool down = false;
    if (getKeyStatus(key) == 1) {
        down = true;
    }
    return down;
}

该如何进行呢?我的主要问题是我似乎无法连接窗口和输入类。我应该使用继承还是朋友类。我应该在window类中(我假设是)使用glfw的回调,还是应该将其移至输入类?如何连接这两个类,这样我就不必始终使用窗口指针,例如“ isKeyDown(GLFWwindow * window,Key keycode)”,而仅使用“ isKeyDown(Key keycode)”。如果不是太多,请问有人可以写一个简单的输入类吗?

预先感谢

1 个答案:

答案 0 :(得分:0)

要指出的一件事是GLFW同时提供了轮询和基于回调的输入处理。在您的示例中,您同时使用了两种方法:轮询用于处理 A B 键,以及用于处理转义键的回调。我相信您会发现在创建单独的输入类(对于键盘和鼠标)时,回调将更易于使用。

有许多方法可以使用GLFW的回调方法创建 KeyInput 类。这是我首选的技术(编写为适合您的代码)。它允许多个 KeyInput 实例(不同于单例),这意味着您可以为UI键使用 KeyInput 实例, -游戏键等

总结:每个 KeyInput 实例监视用户在构造时定义的键列表的按下状态。它具有一个getter和setter来访问任何键的按下状态(尽管getter和setter仅适用于受监视的键)。每当调用GLFW键输入回调(静态)时,它都会为 KeyInput 所有实例调用该设置方法。实例存储在静态向量中,该向量在构造时添加到实例中,并在破坏时从中删除。

Input.h

#include "../extern/GLFW/glfw3.h"
#include <map>
#include <vector>

class KeyInput {
  // Main KeyInput functionality
  public:
    // Takes a list of which keys to keep state for
    KeyInput(std::vector<int> keysToMonitor);
    ~KeyInput();
    // If this KeyInput is enabled and the given key is monitored,
    // returns pressed state.  Else returns false.
    bool getIsKeyDown(int key);
    // See _isEnabled for details
    bool getIsEnabled() { return _isEnabled; }
    void setIsEnabled(bool value) { _isEnabled = value; }
  private:
    // Used internally to update key states.  Called by the GLFW callback.
    void setIsKeyDown(int key, bool isDown);
    // Map from monitored keyes to their pressed states
    std::map<int, bool> _keys;
    // If disabled, KeyInput.getIsKeyDown always returns false
    bool _isEnabled;

  // Workaround for C++ class using a c-style-callback
  public:
    // Must be called before any KeyInput instances will work
    static void setupKeyInputs(Window& window);
  private:
    // The GLFW callback for key events.  Sends events to all KeyInput instances
    static void callback(
      GLFWwindow* window, int key, int scancode, int action, int mods);
    // Keep a list of all KeyInput instances and notify them all of key events
    static std::vector<KeyInput*> _instances;
};

Input.cpp

#include "KeyInput.h"
#include <algorithm>

std::vector<KeyInput*> KeyInput::_instances;

KeyInput::KeyInput(std::vector<int> keysToMonitor) : _isEnabled(true) {
  for (int key : keysToMonitor) {
    _keys[key] = false;
  }
  // Add this instance to the list of instances
  KeyInput::_instances.push_back(this);
}

KeyInput::~KeyInput() {
  // Remove this instance from the list of instances
  _instances.erase(std::remove(_instances.begin(), _instances.end(), this), _instances.end());
}

bool KeyInput::getIsKeyDown(int key) {
  bool result = false;
  if (_isEnabled) {
    std::map<int,bool>::iterator it = _keys.find(key);
    if (it != _keys.end()) {
      result = _keys[key];
    }
  }
  return result;
}

void KeyInput::setIsKeyDown(int key, bool isDown) {
  std::map<int,bool>::iterator it = _keys.find(key);
  if (it != _keys.end()) {
    _keys[key] = isDown;
  }
}

void KeyInput::setupKeyInputs(Window& window) {
  glfwSetKeyCallback(window.getWindow(), KeyInput::callback);
}

void KeyInput::callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
  // Send key event to all KeyInput instances
  for (KeyInput* keyInput : _instances) {
    keyInput->setIsKeyDown(key, action != GLFW_RELEASE);
  }
}