I am creating a 3D space shooter using OpenGL. I have a camera that is set to follow the player’s spaceship. I have managed to keep it at a certain distance and rotate together with the spaceship on the Y axis. See the code bellow for the camera :
float CalculateHorizontalDistance() {
if (!mpPlayer) return 0.f;
return distanceFromPlayer * glm::cos(glm::radians(-UpAngle));
}
float CalculateVerticalDistance() {
if (!mpPlayer) return 0.f;
return distanceFromPlayer * glm::sin(glm::radians(-UpAngle));
}
void calculateCameraPosition(float horizDistance, float verticDistance)
{
if (!mpPlayer) return;
float theta = mpPlayer->GetRotationY() + angleAroundPlayer;
float offsetX = horizDistance * glm::sin(glm::radians(theta));
float offsetZ = horizDistance * glm::cos(glm::radians(theta));
Position.x = mpPlayer->GetPosition().x - offsetX;
Position.y = mpPlayer->GetPosition().y + verticDistance;
Position.z = mpPlayer->GetPosition().z - offsetZ;
}
Also the update and update vectors
void Update() {
float horizDistance = CalculateHorizontalDistance();
float vertDistance = CalculateVerticalDistance();
calculateCameraPosition(horizDistance, vertDistance);
if (mpPlayer)
{
RightAngle = 180.f - (mpPlayer->GetRotationY() + angleAroundPlayer);
}
updateCameraVectors();
}
void updateCameraVectors()
{
// Yaw
glm::quat aroundY = glm::angleAxis(glm::radians(-RightAngle), glm::vec3(0, 1, 0));
// Pitch
glm::quat aroundX = glm::angleAxis(glm::radians(UpAngle), glm::vec3(1, 0, 0));
// Roll
glm::quat aroundZ = glm::angleAxis(glm::radians(RollAngle), glm::vec3(0, 0, 1));
Orientation = aroundY * aroundX * aroundZ;
glm::quat qF = Orientation * glm::quat(0, 0, 0, -1) * glm::conjugate(Orientation);
Front = { qF.x, qF.y, qF.z };
Right = glm::normalize(glm::cross(Front, WorldUp));
Up = glm::normalize(glm::cross(Right, Front));
}
and how I calculate the view
glm::mat4 GetViewMatrix()
{
// You should know the camera move reversely relative to the user input.
// That's the point of Graphics Camera
glm::quat reverseOrient = glm::conjugate(Orientation);
glm::mat4 rot = glm::mat4_cast(reverseOrient);
glm::mat4 translation = glm::translate(glm::mat4(1.0), -Position);
return rot * translation;
}
Although I am near to what I want my camera to do, I am not there yet. I would like the Camera to follow and rotate together with the spaceship and actually follow it. I can not wrap my mind around on how to make it follow the rotations on X and Z axis. Any help on how to achieve this? Code or ideas are welcomed and I hope this is the correct group for these kind of problems.