OpenGL WSAD按键操作和鼠标移动操控摄像机Camera类

WSAD按键操作和鼠标移动

提示:涉及到camera类中的属性请参考上一篇文章:摄像机类的创建

1.按键操作 更新位置

主要用到glfw中的glfwGetKey(GLFWwindow* window,int key);

其作用为:We’ll be using GLFW’s glfwGetKey function that takes the window as input together with a key.The function returns whether this key is currently being pressed.

意思是:我们将使用GLFE中的 glfwGetKey 函数,用它来获取窗口中的按键操作。这个函数返回值为这个按键是否被按下。

例子:glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS
问:参数二int类型?
答:涉及到了define的用法,在glfw里似乎把按键和不同整数对应起来了,或是说把按键的数字和一串可读性高的字符串联系在了一起,所以直接把GLFW_KEY_W写成87也可以,只不过可读性不好。
在这里插入图片描述

因为该函数返回值是true或false,所以将GL_PRESS文本定义为整数1来判断是否按下,符合逻辑。
在这里插入图片描述

void processinput(GLFWwindow* window)
{
	/* We'll be using GLFW's glfwGetKey function that takes the window as input together with a key.
	The function returns whether this key is currently being pressed. */
	if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)//esc按键
	{
		glfwSetWindowShouldClose(window, true);
	}

	if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)//w按键,前移
	{
		camera.speedZ = 1.0f;   //speedXYZ是camera类里面的属性,用来更新camera的位置
	}
	else if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)//s按键,后移
	{
		camera.speedZ = -1.0f;
	}
	else
	{
		camera.speedZ = 0.0f;
	}

	if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)//a按键,左移
	{
		camera.speedX = 1.0f;
	}
	else if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)//d按键,右移
	{
		camera.speedX = -1.0f;
	}
	else
	{
		camera.speedX = 0.0f;
	}

	if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)//q按键,上移
	{
		camera.speedY = 1.0f;
	}
	else if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)//e按键,下移
	{
		camera.speedY = -1.0f;
	}
	else
	{
		camera.speedY = 0.0f;
	}
}

2.鼠标移动 更新朝向

mouse_callback函数是供glfwSetCursorPosCallback(window, mouse_callback)回调的函数,可直接利用glfwSetCursorPosCallback函数获取光标位置,如图参考此链接
在这里插入图片描述

float lastX;
float lastY;

bool firstMouse = true;

//鼠标控制  该函数是供
void mouse_callback(GLFWwindow* window, double xPos, double yPos)
{
	//防止进入时候有很大的偏移量
	if (firstMouse == true)
	{
		lastX = xPos;
		lastY = yPos;
		firstMouse = false;
	}

	float deltaX;  //deltaX控制转角Yaw
	float deltaY;  //deltaY控制转角Pitch
	deltaX = xPos - lastX;
	deltaY = lastY - yPos;  //由于窗口左上角为原点,向上减小,向下增加,所以要用相反数

	lastX = xPos;
	lastY = yPos;

	camera.ProcessMouseMovement(deltaX, deltaY);
	
	//test 用来输出鼠标当前位置和x方向变化量
	printf("%f\n", xPos);
	printf("%f\n", yPos);
	printf("%f\n", deltaX);
}

2.1设置光标模式和获取光标位置

在这里插入图片描述
main函数中

//创建窗口对象 Open GLFW Window
	GLFWwindow* window = glfwCreateWindow(600, 600, "TEXTURE", NULL, NULL);
	if (window == NULL)
	{
		printf("Failed to create GLFW window");
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent(window);

//鼠标移动生效
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
	glfwSetCursorPosCallback(window, mouse_callback);
	
	......
	
while (!glfwWindowShouldClose(window))
	{
		//Process Input 
		//按键操作生效
		processinput(window);	
		.......
	}

至此即可配合camera类对象使用鼠标和按键对视景进行控制。

猜你喜欢

转载自blog.csdn.net/zbx727259615/article/details/124784038