opengl+glfw+glew响应键盘消息

设置键盘消息的回调函数,响应上下左右键,

#include <iostream>
#include <Windows.h>

// GLEW    
#include <GL/glew.h>    

// GLFW 
#include <GLFW/glfw3.h>   

GLuint WIDTH = 400, HEIGHT = 400;
GLfloat gX = 0, gY = 0;

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);

//opengl在glfw中显示规则:
//1.画布中间坐标为0,0。长宽个1.0f个单位,超过1.0f的部分不会被绘制出来
void DrawLine()
{
	glColor4b(99, 38, 13, 90);

	glBegin(GL_LINES);

	glVertex2f(-1 + gX * 4, 1 + gY * 4);//指定第一个点
	glVertex2f(-0.8 + gX * 4, gY * 4 + 0.8);//指定第二个点

	glEnd();//结束
}

void render(GLFWwindow* window)
{
	glClearColor(1.0f, 0.8f, 1.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glEnable(GL_DEPTH_TEST);

	DrawLine();
}

void initWindow(GLFWwindow* window)
{
	glfwMakeContextCurrent(window);

	//设置按键回调
	glfwSetKeyCallback(window, key_callback);
}

void initParam()
{
	//显示规则:窗口左下角坐标为0,0;所以下行代码表示在窗口左下角向右向上的400个像素单位作为画布
	glViewport(0, 0, WIDTH, HEIGHT);//设置显示区域400*400,但是可以拖动改变窗口大小
	glLineWidth(3.0);//设置线条宽度,3个像素
}

int main()
{
	glfwInit();

	GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL", nullptr, nullptr);
	if (window == nullptr)
	{
		std::cout << "Failed to create GLFW window" << std::endl;
		glfwTerminate();
		return -1;
	}

	initWindow(window);

	if (glewInit() != GLEW_OK)
	{
		std::cout << "Failed to initialize GLEW" << std::endl;
		return -1;
	}

	initParam();

	// Game loop    
	while (!glfwWindowShouldClose(window))
	{
		glfwPollEvents();

		render(window);

		glfwSwapBuffers(window);
	}

	// Terminate GLFW, clearing any resources allocated by GLFW.    
	glfwTerminate();
	return 0;
}

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
	if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)//按下esc退出程序
	{
		glfwSetWindowShouldClose(window, GL_TRUE);
	}
	else if (key == GLFW_KEY_LEFT)
	{
		gX -= 0.01;
	}
	else if (key == GLFW_KEY_RIGHT)
	{
		gX += 0.01;
	}
	else if (key == GLFW_KEY_UP)
	{
		gY += 0.01;
	}
	else if (key == GLFW_KEY_DOWN)
	{
		gY -= 0.01;
	}
}

现在可以响应上下左右按键,实现线条在窗口中的上下左右的移动

opengl+glfw+glew响应键盘消息