OpenGL ES3, C++ 11, Android。我有一个实现第三人称相机的物体和相机,当我触摸屏幕时我想让物体朝向相机,所以我为对象有一个变换矩阵和相机的视图矩阵,相机围绕物体旋转,我希望当我触摸屏幕时,物体能够朝向相机旋转,所以我尝试了以下方法:
glm::vec3 up(0, 1, 0);
glm::vec3 camFor(glm::cross(camera.getRight(), up));
GLfloat theta = glm::angle(glm::vec2(camFor.x, camFor.z), glm::vec2(getDirection().x, getDirection().z));
LOGI("game theta %f", theta);
matrix = glm::rotate(matrix, theta, glm::vec3(0.0, 1.0, 0.0));
我获取了物体前向量和相机前向量之间的水平角度,代码如下:
glm :: vec3(matrix [2] [0],matrix [2] [1],matrix [2] [2])
。当相机正好在物体后面时,我第一次得到的θ等于π,这是正确的。然后,我触摸屏幕以触发事件,物体旋转并朝向相机,此时θ变为零。但是,如果我围绕物体旋转相机并再次触发事件,则θ值会变得不可预测。
相机的旋转代码如下:void Camera::rotate(GLfloat xoffset, GLfloat yoffset, glm::vec3& c, double& delta, GLboolean constrainpitch) {
xoffset *= (delta * this->rotSpeed);
yoffset *= (delta * this->rotSpeed);
pitch += yoffset;
yaw += xoffset;
if (constrainpitch) {
if (pitch >= maxPitch) {
pitch = maxPitch;
yoffset = 0;
}
if (pitch <= minPitch) {
pitch = minPitch;
yoffset = 0;
}
}
glm::quat Qx(glm::angleAxis(glm::radians(yoffset), glm::vec3(1.0f, 0.0f, 0.0f)));
glm::quat Qy(glm::angleAxis(glm::radians(xoffset), glm::vec3(0.0f, 1.0f, 0.0f)));
glm::mat4 rotX = glm::mat4_cast(Qx);
glm::mat4 rotY = glm::mat4_cast(Qy);
view = glm::translate(view, c);
view = rotX * view;
view = view * rotY;
view = glm::translate(view, -c);
}
解决方案:
错误在于获取相机矩阵的右向量,以下是正确方式:
glm::vec3& Camera::getRight() {
right = glm::vec3(view[0][0], view[1][0], view[2][0]);
return right;
}