Camera does not move in direction of camera target

50 Views Asked by At

Implementing a simple camera system while learning OpenGL and come across an issue where, when I pitch down or up and move forward the camera goes in the opposite direction of the new camera direction. If I face towards the positive x axis using yaw, the camera moves "forward" towards the negative z axis while looking at the positive x. I'm using a right handed system and have been trying to figure this out for a week and have not managed to understand where I am going wrong. Wondering if anyone has had this issue before and could help me understand where I might be going wrong.

vec3 cameraPos = vec3(0,100,0);
vec3 cameraTarget = vec3(0,0,-20);
vec3 cameraUp = vec3(0,1,0);
void Camera::calculateDirection()
{
    vec3 direction;
    direction.x = std::cos(toRadians(yaw)) * std::cos(toRadians(pitch));
    direction.y = std::sin(toRadians(pitch));
    direction.z = std::sin(toRadians(yaw)) * std::cos(toRadians(pitch));
    cameraTarget = direction.unit();
}
 
void Camera::Update()
{ 
    calculateDirection();
    viewMatrix = constructView(cameraPos, cameraPos + cameraTarget, cameraUp);
}
 
void Renderer::Update()
{
    camera->Update();
}
 
Matrix4 Camera::constructView(const vec3& eye, const vec3& center, const vec3& up)
{   
    vec3 x, y, z;
 
    z = eye - center;
    z = z.unit();
 
    x = up.cross(z);
    x = x.unit();
 
    y = z.cross(x);
    y = y.unit();
 
    Matrix4 orient;
    // x
    orient[0][0] = x.x;
    orient[1][0] = x.y;
    orient[2][0] = x.z;
    orient[3][0] = 0;
 
    // y
    orient[0][1] = y.x;
    orient[1][1] = y.y;
    orient[2][1] = y.z;
    orient[3][1] = 0;
 
    // z
    orient[0][2] = z.x;
    orient[1][2] = z.y;
    orient[2][2] = z.z;
    orient[3][2] = 0;
 
    orient[0][3] = 0;
    orient[1][3] = 0;
    orient[2][3] = 0;
    orient[3][3] = 1;
 
    Matrix4 translation;
    translation[0][0] = 1;
    translation[1][0] = 0;
    translation[2][0] = 0;
    translation[3][0] = 0;
 
    translation[0][1] = 0;
    translation[1][1] = 1;
    translation[2][1] = 0;
    translation[3][1] = 0;
 
    translation[0][2] = 0;
    translation[1][2] = 0;
    translation[2][2] = 1;
    translation[3][2] = 0;
 
    translation[0][3] = -eye.x;
    translation[1][3] = -eye.y;
    translation[2][3] = -eye.z;
    translation[3][3] = 1;
    
    return orient * translation;
 }
 
void Renderer::Render()
{

    // Rotate 90 degrees CCW because models are modelled with y axis as forward and z as up. this rotates back to OpenGL
    WorldMatrix = Matrix4::Identity();
    WorldMatrix = Matrix4::RotateX(90.0);
    
    // Apply matrix to model vertices
    Model floor("floor.obj");
    auto matrix = viewMatrix * WorldMatrix;
    floor.Render(matrix);
}
0

There are 0 best solutions below