【发布时间】:2019-08-29 14:12:02
【问题描述】:
我正在做我的一个小项目,我基本上是在创建我自己的 c++ 游戏引擎/框架来创建图形和/或简单的游戏。我将 OpenGL 与 GLFW 一起使用。我的目标是拥有类似于各种图形框架的东西,例如 raylib 或 openFrameworks(但当然被剥离了)
实际上到目前为止一切正常,但我不知道如何正确地将输入与窗口类分开,因为窗口句柄输入对我来说似乎相当笨拙,只会使窗口类变得混乱。
这是对我的窗口类的快速过度简化的重新创建。 (我没有在键码中包含枚举类。)
#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;
}
我该如何着手呢?我的主要问题是我似乎无法连接我的窗口和输入类。我应该使用继承类还是朋友类。我应该在窗口类(我假设)中有glfw的回调还是应该将它们移动到输入类?如何连接这两个类,这样我就不必总是使用窗口指针,例如“isKeyDown(GLFWwindow* window, Key keycode)”,而是只使用“isKeyDown(Key keycode)”。如果不是太多,有人可以写一个简单的输入类吗?
提前致谢
【问题讨论】:
标签: c++ opengl input game-engine glfw