OpenGL ES3, C++ 11, Android, I have an object and a camera implementing third person camera so I want to make the object looks towards the camera when I touch the screen so I have a transformation matrix for the object and the view matrix of the camera, the camera rotates around the object , I want the object rotates towards the camera when I touch the screen so I tried the following:
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));
I get the horizontal angle between the object forward vector and the camera forward one which is glm::vec3(matrix[2][0], matrix[2][1], matrix[2][2])
, first time when the camera is exactly behind the object I get theta equal to pi and that is right then I touch the screen to fire the event the object rotates and looks to the camera as expected and theta become zero, if I rotate the camera around the object and fire the event again it gives unexpected values for theta.
the rotation code of the camera is:
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);
}
Solution:
the error was in getting the Right vector of the camera matrix this is the correct
glm::vec3& Camera::getRight() {
right = glm::vec3(view[0][0], view[1][0], view[2][0]);
return right;
}
the error was in getting the Right vector of the camera matrix this is the correct
glm::vec3& Camera::getRight() {
right = glm::vec3(view[0][0], view[1][0], view[2][0]);
return right;
}