前提
跟着LeanOpenGL网站实现了相机的基本操作(前、后、左右移动)、鼠标响应
原理
环绕中心旋转的本质是在每一帧的距离变化上保持相机位置和中心点的距离不变,其实就是保持相机的每一帧的位置都在这个半径为R的球面上。
在初始状态,我们已在半径为R的球面上,但我们的输入只有二维屏幕X、Y两个输入,如何实现环绕中心点移动呢?
将鼠标滑动作为相机在球面切线上运动的输入,此时任意的左右移动都会脱离这个球面,而我们要做的其实就是把脱离的距离给减掉,于是就回到了球面上。
Code
void ModelAssebleWidget::mouseMoveEvent(QMouseEvent *event) {
if (event->buttons() & Qt::LeftButton) {
auto pos = event->localPos();
float xOffset = pos.x() - lastX; //鼠标在屏幕上滑动的X轴距离
float yOffset = pos.y() - lastY;//鼠标在屏幕上滑动的Y轴距离
lastX = pos.x();
lastY = pos.y();
currentCamera->Move(currentCamera->right * xOffset*0.05f); //给一个参数因子作为镜头移动的灵敏度
currentCamera->Move(currentCamera->up * yOffset*0.05f);
currentCamera->lookToPos(glm::vec3(0));
float moveDistance = glm::distance(currentCamera->position,glm::vec3(0))-camRadius; //计算需要矫正的前向距离
}
}