Skip to content
Lulezer edited this page Apr 2, 2025 · 2 revisions

Echlib Camera System Guide

Introduction

This guide explains how to implement a camera system in Echlib, ensuring smooth player movement and camera tracking. The example provided demonstrates how to keep the camera centered on the player while supporting zoom functionality.


Setting Up the Window

Before implementing the camera system, we need to create a window and set up the environment:

#include <echlib.h>
#include <cmath>  // For sqrt
#include <iostream>

using namespace ech;

int main()
{
    float PlayerX = 50.0f, PlayerY = 50.0f;
    float Speed = 400.0f;
    int WindowWidth = 800, WindowHeight = 800;
    int BasePlayerWidth = 100, BasePlayerHeight = 100; // Store original size

    MakeWindow(WindowWidth, WindowHeight, "Echlib Camera Example");
    SetTargetFps(60);

    LoadTexture(RESOURCES_PATH "Player/Player_Back.png", "player");
    LoadTexture(RESOURCES_PATH "Map/Map.png", "background");

    camera.x = PlayerX - (WindowWidth / 2.0f);
    camera.y = PlayerY - (WindowHeight / 2.0f);
    camera.zoom = 5.0f;

Player Movement

We implement movement using IsKeyHeld() to check for user input:

    while (!WindowShouldClose())
    {
        float DeltaTime = GetDeltaTime();
        float moveX = 0.0f, moveY = 0.0f;

        if (IsKeyHeld(KEY_RIGHT)) moveX += 1.0f;
        if (IsKeyHeld(KEY_LEFT)) moveX -= 1.0f;
        if (IsKeyHeld(KEY_UP)) moveY += 1.0f;
        if (IsKeyHeld(KEY_DOWN)) moveY -= 1.0f;

        float magnitude = sqrt(moveX * moveX + moveY * moveY);
        if (magnitude > 0.0f)
        {
            moveX /= magnitude;
            moveY /= magnitude;
        }

        PlayerX += moveX * Speed * DeltaTime;
        PlayerY += moveY * Speed * DeltaTime;

Camera Tracking & Zoom

The camera follows the player while maintaining zoom functionality:

        camera.x = PlayerX - (WindowWidth / 2.0f) / camera.zoom;
        camera.y = PlayerY - (WindowHeight / 2.0f) / camera.zoom;

Rendering

Finally, we render the background and player relative to the camera position:

        StartDrawing();
        ClearBackground(GRAY);

        DrawTexturedRectangle(-camera.x, -camera.y, 2000, 2000, "background");
        DrawTexturedRectangle(
            PlayerX - camera.x, PlayerY - camera.y,
            BasePlayerWidth * camera.zoom, BasePlayerHeight * camera.zoom,
            "player"
        );

        EndDrawing();
    }

Conclusion

This example demonstrates how to:

  • Implement smooth player movement

  • Keep the camera centered on the player

  • Apply zoom effects without distorting the player size

  • Collision

Yo

Clone this wiki locally