我将创建一个具有您的(非静态)keyCallback
方法交互性的类,然后创建您的应用程序类的一个实例,并在另一个静态 keycallback 函数内部调用应用程序实例上的 keycallback 方法,然后将其传递给glfwSetKeyCallback
. 这是我在开始使用它的新项目时经常构建的模板:
#include <iostream>
#include <string>
#include <GLFW/glfw3.h>
// obviously create headers with declarations seperate from definitions
// when spanning across multiple files, but for sake of brevity they
// have not been used.
// application.cpp
class Application {
public:
GLFWwindow *window;
Application(std::string title) {
// boilerplate stuff (ie. basic window setup, initialize OpenGL) occurs in abstract class
glfwInit();
window = glfwCreateWindow(640, 480, title.c_str(), NULL, NULL);
glfwMakeContextCurrent(window);
}
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
// basic window handling
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
std::cout << "exiting..." << std::endl;
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
// must be overridden in derived class
virtual void update() = 0;
void gameLoop() {
while (!glfwWindowShouldClose(window)) {
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// update function gets called here
update();
glfwPollEvents();
glfwSwapBuffers(window);
}
glfwTerminate();
}
};
// myapp.cpp
class MyApp : public Application {
public:
MyApp(std::string title) : Application(title) {
// my application specific state gets initialized here
}
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
Application::keyCallback(window, key, scancode, action, mods);
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) {
// anotherClass.Draw();
std::cout << "space pressed!" << std::endl;
}
}
void update() override {
// player.Update();
// anotherClass.Draw();
}
};
Application* getApplication() {
return new MyApp("MyApp");
}
// main.cpp
// extern Application* getApplication();
Application *app;
static void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) {
MyApp* myApp = (MyApp*)app;
myApp->keyCallback(window, key, scancode, action, mods);
}
int main() {
app = getApplication();
glfwSetKeyCallback(app->window, keyCallback);
app->gameLoop();
}