ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > C / raylib > raylib Camera2D 줌, 회전, 룸 바운드(Room Clamp) 및 부드러운 타깃 추적raylib Camera2D Zoom, Room Bounds Clamping, and Smooth Target Tracking
C / raylib Beginner C99 / raylib 5.0+

raylib Camera2D 줌, 회전, 룸 바운드(Room Clamp) 및 부드러운 타깃 추적raylib Camera2D Zoom, Room Bounds Clamping, and Smooth Target Tracking

플레이어를 화면 중앙에 부드럽게 유지하고 레벨 경계선 밖으로 카메라가 벗어나지 않도록 클램핑하는 raylib 2D 카메라 제어 구현입니다.A raylib 2D camera controller that smoothly tracks the player around the screen center while clamping the viewport inside level boundaries.

#C #raylib #Camera2D #GameFeel #2DPlatformer
핵심 개념raylib의 Camera2D 구조체는 offset(화면 중심 앵커), target(월드 상 추적 대상 좌표), rotation, zoom 네 가지 파라미터로 동작합니다. 지수 감쇠 보간과 맵 경계선 클램핑(Clamp)을 결합하면 급격한 이동 시에도 시야가 튀지 않고 레벨 바깥의 빈 배경이 노출되지 않는 2D 카메라를 구성할 수 있습니다.
Key Conceptraylib's Camera2D struct operates on four parameters: offset (screen-space anchor), target (world-space focus point), rotation, and zoom. Combining exponential decay interpolation with room boundary clamping (Clamp) keeps camera motion smooth during rapid movement and prevents empty space outside the level from appearing on screen.

1. 부드러운 타깃 팔로우 및 바운드 클램프 C 코드1. Smooth Target Follow and Bound Clamping in C

camera_smoothing.c
#include "raylib.h"
#include "raymath.h"
#include <math.h>

void UpdateSmoothCamera(Camera2D *camera, Vector2 playerPos, Rectangle mapBounds, float dt) {
    // 1. 프레임률에 독립적인 지수 감쇠 보간 (Smooth follow)
    float smoothSpeed = 8.0f;
    float t = 1.0f - expf(-smoothSpeed * dt);
    camera->target.x = Lerp(camera->target.x, playerPos.x, t);
    camera->target.y = Lerp(camera->target.y, playerPos.y, t);

    // 2. 맵 경계선 클램핑 (현재 줌 배율이 반영된 뷰포트 절반 크기 계산)
    Vector2 halfView = {
        (GetScreenWidth() / 2.0f) / camera->zoom,
        (GetScreenHeight() / 2.0f) / camera->zoom
    };

    // 맵이 화면보다 클 때만 경계 클램핑 수행, 작으면 맵 중앙 고정
    if (mapBounds.width > halfView.x * 2.0f) {
        camera->target.x = Clamp(camera->target.x, mapBounds.x + halfView.x,
                                 mapBounds.x + mapBounds.width - halfView.x);
    } else {
        camera->target.x = mapBounds.x + mapBounds.width * 0.5f;
    }

    if (mapBounds.height > halfView.y * 2.0f) {
        camera->target.y = Clamp(camera->target.y, mapBounds.y + halfView.y,
                                 mapBounds.y + mapBounds.height - halfView.y);
    } else {
        camera->target.y = mapBounds.y + mapBounds.height * 0.5f;
    }
}
camera_smoothing.c
#include "raylib.h"
#include "raymath.h"
#include <math.h>

void UpdateSmoothCamera(Camera2D *camera, Vector2 playerPos, Rectangle mapBounds, float dt) {
    // 1. Frame-rate independent exponential decay interpolation (Smooth follow)
    float smoothSpeed = 8.0f;
    float t = 1.0f - expf(-smoothSpeed * dt);
    camera->target.x = Lerp(camera->target.x, playerPos.x, t);
    camera->target.y = Lerp(camera->target.y, playerPos.y, t);

    // 2. Clamp to map bounds (accounting for zoom-scaled half-viewport size)
    Vector2 halfView = {
        (GetScreenWidth() / 2.0f) / camera->zoom,
        (GetScreenHeight() / 2.0f) / camera->zoom
    };

    // Clamp only when the map is larger than the viewport; otherwise center on the room
    if (mapBounds.width > halfView.x * 2.0f) {
        camera->target.x = Clamp(camera->target.x, mapBounds.x + halfView.x,
                                 mapBounds.x + mapBounds.width - halfView.x);
    } else {
        camera->target.x = mapBounds.x + mapBounds.width * 0.5f;
    }

    if (mapBounds.height > halfView.y * 2.0f) {
        camera->target.y = Clamp(camera->target.y, mapBounds.y + halfView.y,
                                 mapBounds.y + mapBounds.height - halfView.y);
    } else {
        camera->target.y = mapBounds.y + mapBounds.height * 0.5f;
    }
}

2. 실무 적용 및 주의사항2. Practical Considerations and Caveats

  • 프레임률 독립적인 지수 보간 적용: Lerp(current, target, speed * dt)에 단순히 speed * dt를 넣으면 프레임 드랍 시 speed * dt > 1.0f가 되어 목표 좌표를 지나치는 오버슈트가 발생할 수 있습니다. 1.0f - expf(-speed * dt) 공식을 사용하면 주사율에 관계없이 일정한 감쇠 곡선을 유지합니다.
  • 작은 방(Small Room)에서의 Clamp 역전 방어: 맵의 가로·세로 크기가 화면 뷰포트(halfView * 2.0f)보다 작은 작은 방에서는 min > max가 되어 카메라가 진동하므로, 분기문을 통해 맵이 뷰포트보다 작을 때는 방 정중앙(mapBounds.x + mapBounds.width * 0.5f)으로 고정해야 합니다.
  • 해상도 변경 시 camera.offset 갱신: 창 크기가 변경(IsWindowResized())될 때 camera.offset = (Vector2){ GetScreenWidth() / 2.0f, GetScreenHeight() / 2.0f }를 함께 갱신해야 타깃이 화면 정중앙에 유지됩니다.
  • Use Frame-Rate Independent Exponential Smoothing: Passing speed * dt directly as the Lerp factor can exceed 1.0f during frame drops and overshoot the target. Using 1.0f - expf(-speed * dt) guarantees consistent damping across any refresh rate.
  • Guard Against Inverted Clamp Ranges in Small Rooms: When a room's width or height is smaller than the visible viewport (halfView * 2.0f), min exceeds max in Clamp. Explicitly lock camera->target to the room midpoint in that case.
  • Update camera.offset on Window Resize: Whenever IsWindowResized() returns true, recalculate camera.offset = (Vector2){ GetScreenWidth() / 2.0f, GetScreenHeight() / 2.0f } so the target stays centered.

Camera2D의 지수 감쇠 추적과 뷰포트 크기를 반영한 경계선 클램핑을 적용하면, 줌 배율이 실시간으로 변하는 상황에서도 플레이어 시야를 안정적으로 제어할 수 있습니다.

Combining exponential damping with zoom-aware viewport clamping keeps the Camera2D view stable across varying room dimensions and dynamic zoom levels.

참고자료 & 관련 링크