Skip to main content

Overview

The Camera class represents a camera in 3D space, capable of generating view and projection matrices. It has built-in controls for moving and looking with native support for both perspective and orthographic projections.

Camera Class

Constructor

Camera();
Constructs a new Camera object with default values:
  • Position: {0.0f, 0.0f, 3.0f}
  • Target: {0.0f, 0.0f, 0.0f}
  • FOV: 45.0f
  • Near clip: 0.5f
  • Far clip: 1000.0f

Properties

position
Position3d
The position of the camera in 3D space.
target
Point3d
The point where the camera is looking at in 3D space.
fov
float
default:"45.0f"
The field of view of the camera in degrees. Used for perspective projection.
nearClip
float
default:"0.5f"
The near clipping plane distance. Everything closer than this value will be clipped.
farClip
float
default:"1000.0f"
The far clipping plane distance. Everything farther than this value will be clipped.
orthographicSize
float
default:"5.0f"
The size of the orthographic projection. Used when useOrthographic is true.
movementSpeed
float
default:"2.0f"
The speed at which the camera moves through the scene.
mouseSensitivity
float
default:"0.1f"
The factor by which the camera’s mouse input is scaled.
lookSmoothness
float
default:"0.15f"
The factor to determine how smoothly the camera looks at the target. Lower values = smoother.
useOrthographic
bool
default:"false"
Whether the camera is using orthographic projection. When false, uses perspective projection.
focusDepth
float
default:"20.0f"
The depth value at which objects are in perfect focus for depth of field effects.
focusRange
float
default:"10.0f"
The range around focusDepth where objects gradually transition from sharp to blurred.

Transform Methods

move

void move(const Position3d &delta);
Move the camera by a delta in 3D space.
delta
const Position3d&
The delta by which to move the camera.

setPosition

void setPosition(const Position3d &newPosition);
Sets the position of the camera in 3D space.
newPosition
const Position3d&
The new position to set the camera to.

setPositionKeepingOrientation

void setPositionKeepingOrientation(const Position3d &newPosition);
Sets the camera position while maintaining its current orientation (yaw and pitch).
newPosition
const Position3d&
The new position to set the camera to.

lookAt

void lookAt(const Point3d &newTarget);
Sets the point where the camera is looking at in 3D space.
newTarget
const Point3d&
The new target point to look at.

moveTo

void moveTo(Direction3d direction, float speed);
Moves the camera in a specified direction at a given speed.
direction
Direction3d
The direction in which to move the camera.
speed
float
The speed at which to move the camera.

Input Handling Methods

update

void update(Window &window);
Updates the camera’s position and orientation based on user input from keyboard (WASD for movement).
window
Window&
The window from which to get input.

updateLook

void updateLook(Window &window, Movement2d movement);
Updates the camera’s look direction based on mouse movement.
window
Window&
The window from which to get input.
movement
Movement2d
The movement of the mouse.

updateZoom

void updateZoom(Window &window, Movement2d offset);
Updates the camera’s zoom level based on scroll input. Adjusts the field of view for perspective cameras.
window
Window&
The window from which to get input.
offset
Movement2d
The offset of the scroll.

Matrix Methods

calculateViewMatrix

glm::mat4 calculateViewMatrix() const;
Calculates and returns the view matrix based on the camera’s position and orientation.
return
glm::mat4
The calculated view matrix.

Utility Methods

getFrontVector

Normal3d getFrontVector() const;
Get the front vector of the camera, representing the direction it is facing.
return
Normal3d
The front vector of the camera (normalized).

getVelocity

Magnitude3d getVelocity() const;
Get the velocity of the camera based on its front vector and movement speed.
return
Magnitude3d
The velocity of the camera.

ViewInformation Structure

Bundle of camera state values passed to systems that need view context (e.g., weather, atmosphere).
position
Position3d
Current world-space position of the observing camera.
target
Position3d
World-space point the camera is tracking or looking at.
time
float
Absolute engine time, typically measured in seconds.
deltaTime
float
Time elapsed since the previous update.

Example Usage

Basic Camera Setup

// Create a camera instance
Camera camera;

// Set the camera position
camera.setPosition({0.0f, 2.0f, 5.0f});

// Make the camera look at the origin
camera.lookAt({0.0f, 0.0f, 0.0f});

// Configure camera properties
camera.fov = 60.0f;
camera.movementSpeed = 5.0f;
camera.mouseSensitivity = 0.15f;

// Assign camera to window
window.setCamera(&camera);

Camera with Input Handling

class MyScene : public Scene {
private:
    Camera camera;
    
public:
    void initialize(Window &window) override {
        // Set up camera
        camera.setPosition({0.0f, 5.0f, 10.0f});
        camera.lookAt({0.0f, 0.0f, 0.0f});
        camera.movementSpeed = 3.0f;
        
        window.setCamera(&camera);
    }
    
    void update(Window &window) override {
        // Update camera position based on keyboard input
        camera.update(window);
    }
    
    void onMouseMove(Window &window, Movement2d movement) override {
        // Update camera look direction based on mouse
        camera.updateLook(window, movement);
    }
    
    void onMouseScroll(Window &window, Movement2d offset) override {
        // Update camera zoom based on scroll wheel
        camera.updateZoom(window, offset);
    }
};

Perspective vs Orthographic

// Perspective camera (default) - for 3D games
Camera perspectiveCamera;
perspectiveCamera.useOrthographic = false;
perspectiveCamera.fov = 75.0f;
perspectiveCamera.nearClip = 0.1f;
perspectiveCamera.farClip = 1000.0f;

// Orthographic camera - for 2D games or UI
Camera orthographicCamera;
orthographicCamera.useOrthographic = true;
orthographicCamera.orthographicSize = 10.0f; // Size of visible area
orthographicCamera.nearClip = -100.0f;
orthographicCamera.farClip = 100.0f;

Custom Camera Movement

class CustomCameraController : public Component {
private:
    Camera* camera;
    float orbitRadius = 10.0f;
    float orbitSpeed = 1.0f;
    float angle = 0.0f;
    
public:
    CustomCameraController(Camera* cam) : camera(cam) {}
    
    void update(float deltaTime) override {
        Window* window = getWindow();
        if (!window || !camera) return;
        
        // Orbit around origin
        angle += orbitSpeed * deltaTime;
        
        float x = orbitRadius * cos(angle);
        float z = orbitRadius * sin(angle);
        
        camera->setPosition({x, 5.0f, z});
        camera->lookAt({0.0f, 0.0f, 0.0f});
    }
};

// Usage
Camera camera;
CustomCameraController controller(&camera);
myGameObject.addComponent(controller);

First-Person Camera

class FirstPersonCamera : public Component {
private:
    Camera* camera;
    CoreObject* player;
    float height = 1.8f; // Eye height
    
public:
    FirstPersonCamera(Camera* cam, CoreObject* playerObj) 
        : camera(cam), player(playerObj) {}
    
    void update(float deltaTime) override {
        Window* window = getWindow();
        if (!window || !camera || !player) return;
        
        // Keep camera at player position + eye height
        Position3d playerPos = player->getPosition();
        camera->setPositionKeepingOrientation({
            playerPos.x,
            playerPos.y + height,
            playerPos.z
        });
        
        // Handle player movement based on camera direction
        Normal3d forward = camera->getFrontVector();
        forward.y = 0.0f; // Keep movement horizontal
        forward = Normal3d::fromGlm(glm::normalize(forward.toGlm()));
        
        float moveSpeed = 5.0f * deltaTime;
        
        if (window->isKeyPressed(Key::W)) {
            player->move(forward * moveSpeed);
        }
        if (window->isKeyPressed(Key::S)) {
            player->move(forward * -moveSpeed);
        }
    }
};

Third-Person Camera

class ThirdPersonCamera : public Component {
private:
    Camera* camera;
    CoreObject* target;
    float distance = 5.0f;
    float height = 2.0f;
    
public:
    ThirdPersonCamera(Camera* cam, CoreObject* targetObj)
        : camera(cam), target(targetObj) {}
    
    void update(float deltaTime) override {
        if (!camera || !target) return;
        
        // Position camera behind and above target
        Position3d targetPos = target->getPosition();
        Rotation3d targetRot = target->getRotation();
        
        // Calculate offset based on target rotation
        float angleRad = glm::radians(targetRot.y);
        float offsetX = distance * sin(angleRad);
        float offsetZ = distance * cos(angleRad);
        
        camera->setPosition({
            targetPos.x - offsetX,
            targetPos.y + height,
            targetPos.z - offsetZ
        });
        
        camera->lookAt(targetPos);
    }
};

Smooth Camera Follow

class SmoothFollow : public Component {
private:
    Camera* camera;
    CoreObject* target;
    Position3d offset = {0.0f, 5.0f, -10.0f};
    float smoothSpeed = 5.0f;
    
public:
    SmoothFollow(Camera* cam, CoreObject* targetObj)
        : camera(cam), target(targetObj) {}
    
    void update(float deltaTime) override {
        if (!camera || !target) return;
        
        // Calculate desired position
        Position3d targetPos = target->getPosition();
        Position3d desiredPos = {
            targetPos.x + offset.x,
            targetPos.y + offset.y,
            targetPos.z + offset.z
        };
        
        // Smoothly interpolate to desired position
        Position3d currentPos = camera->position;
        float t = smoothSpeed * deltaTime;
        
        Position3d smoothedPos = {
            currentPos.x + (desiredPos.x - currentPos.x) * t,
            currentPos.y + (desiredPos.y - currentPos.y) * t,
            currentPos.z + (desiredPos.z - currentPos.z) * t
        };
        
        camera->setPosition(smoothedPos);
        camera->lookAt(targetPos);
    }
};

Camera Types Summary

Perspective Camera

  • Use Case: 3D games, realistic rendering
  • Key Properties: fov, nearClip, farClip
  • Characteristics: Objects appear smaller as they get farther away

Orthographic Camera

  • Use Case: 2D games, UI, technical drawings
  • Key Properties: orthographicSize, nearClip, farClip
  • Characteristics: No perspective distortion, parallel projection

Depth of Field

The camera supports depth of field effects through the focusDepth and focusRange properties:
Camera camera;
camera.focusDepth = 15.0f;  // Objects at 15 units are in perfect focus
camera.focusRange = 5.0f;    // Blur gradually increases beyond this range

// Enable depth of field in the rendering pipeline
window.enableDepthOfField(true);
Depth of field effects require enabling the appropriate post-processing in your rendering pipeline.

Build docs developers (and LLMs) love