2
votes

I have a camera class , It has rotation and position and a method to generate a view matrix from the position and rotation , etch frame the camera sends the view matrix to the renderer. (same for the projection matrix but that's not changing much).

class Renderer;
class Camera
{
    Renderer& m_renderer;
    glm::mat4 GetViewMatrix();
public:
    glm::vec3 position;
    glm::vec3 rotation;
    float Fov;

    Camera(Renderer& renderer,float Fov, int width , int height);
    void MoveCamera(glm::vec3 direction);
    void RotateCamera(glm::vec3 direction);
    void Update();
};

what I want to do is to call "MoveCamera" :

void Camera::MoveCamera(glm::vec3 direction)
{
    this->position += direction;
}

with the forwardDirection*deltaTime*speed from my main loop. my problem is creating a forward direction vector from my rotation and position. rotation is a vector3 with degrees that are used to create a view matrix like this :

glm::mat4 Camera::GetViewMatrix()
{
    glm::mat4 matRoll = glm::mat4(1.0f);
    glm::mat4 matPitch = glm::mat4(1.0f);
    glm::mat4 matYaw = glm::mat4(1.0f);
    matRoll = glm::rotate(matRoll,glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
    matPitch = glm::rotate(matPitch, glm::radians(rotation.x), glm::vec3(0.0f, 1.0f, 0.0f));
    matYaw = glm::rotate(matYaw, glm::radians(rotation.y), glm::vec3(1.0f, 0.0f, 0.0f));
    glm::mat4 rotate = matRoll * matPitch * matYaw;
    glm::mat4 translate = glm::mat4(1.0f);
    translate = glm::translate(translate ,-position);
    return   rotate*translate ;
}

So how should I go about making a forward vector out of my position and rotation in this case ?

1
I really advice against using Euler angles for this use case. They have a bunch of disadvantages and negligible benefits in this case. Anyway, the forward direction is usually the third row of the view matrix (or its negative).Nico Schertler

1 Answers

6
votes

You can extract it from your camera view matrix.

Once you have your camera transformation matrix in world space, you can invert it to get the view matrix

You are using glm which uses column-major matrices so you can just grab the second column of the inverted matrix and normalise it to get a direction.

const mat4 inverted = glm::inverse(transformationMatrix);
const vec3 forward = normalize(glm::vec3(inverted[2]));