ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > C / raylib > raylib 기반 델타 타임 누적 고정 프레임 레이트 게임 루프Fixed Timestep Accumulator Game Loop in raylib
C / raylib Intermediate C99 / raylib 5.0+

raylib 기반 델타 타임 누적 고정 프레임 레이트 게임 루프Fixed Timestep Accumulator Game Loop in raylib

물리 연산의 결정론(Determinism)을 확보하기 위해 렌더링 주기에 상관없이 일정한 시간 간격(Fixed dt)으로 로직을 갱신하는 Accumulator 기반 게임 루프입니다.An accumulator-based game loop pattern in C and raylib that steps physics at a constant time interval (Fixed dt) regardless of display refresh rate to ensure deterministic simulation.

#C #raylib #Game Loop #Architecture #Physics
핵심 개념모니터 주사율(60Hz, 144Hz, 240Hz)에 따라 물리 적분 간격이 달라지면 플레이어 점프 높이나 충돌 판정 결과가 달라집니다. 'Fix Your Timestep' 패턴은 가변 프레임 타임을 누적기(Accumulator)에 더한 뒤, 고정된 시간 틱($dt = 1/60\text{s}$) 단위로만 물리 시뮬레이션을 실행하여 일관된 물리 결과를 보장합니다.
Key ConceptWhen physics integration intervals vary with monitor refresh rates (60Hz, 144Hz, 240Hz), player jump heights and collision outcomes become inconsistent. The 'Fix Your Timestep' pattern accumulates variable frame deltas into an accumulator and advances the physics simulation strictly in fixed ticks ($dt = 1/60\text{s}$).

1. raylib 고정 델타 타임 메인 루프1. raylib Fixed Timestep Main Loop

fixed_loop.c
#include "raylib.h"

#define FIXED_DT (1.0f / 60.0f) // 60Hz 고정 물리 갱신 주기

int main(void)
{
    InitWindow(1280, 720, "Fixed Timestep Loop - LYSC");
    SetTargetFPS(0); // 가변 주사율 렌더링 허용

    float accumulator = 0.0f;

    while (!WindowShouldClose())
    {
        float frameTime = GetFrameTime();
        // 나선형 사망(Spiral of Death) 방지: 프레임 드랍 시 최대 누적 상한 제한
        if (frameTime > 0.25f) frameTime = 0.25f;
        accumulator += frameTime;

        // 고정 시간 단계 물리 시뮬레이션
        while (accumulator >= FIXED_DT)
        {
            // PhysicsUpdate(FIXED_DT);
            accumulator -= FIXED_DT;
        }

        // 잔여 시간 비율 alpha (이전 물리 좌표와 현재 물리 좌표 사이 렌더링 보간용)
        float alpha = accumulator / FIXED_DT;

        BeginDrawing();
        ClearBackground(RAYWHITE);
        DrawText("Fixed Timestep Running", 20, 20, 20, DARKGRAY);
        DrawFPS(20, 50);
        EndDrawing();
    }

    CloseWindow();
    return 0;
}
fixed_loop.c
#include "raylib.h"

#define FIXED_DT (1.0f / 60.0f) // 60Hz fixed physics update interval

int main(void)
{
    InitWindow(1280, 720, "Fixed Timestep Loop - LYSC");
    SetTargetFPS(0); // Allow variable refresh rate rendering

    float accumulator = 0.0f;

    while (!WindowShouldClose())
    {
        float frameTime = GetFrameTime();
        // Prevent Spiral of Death: clamp maximum accumulated delta on frame drops
        if (frameTime > 0.25f) frameTime = 0.25f;
        accumulator += frameTime;

        // Fixed-step physics simulation
        while (accumulator >= FIXED_DT)
        {
            // PhysicsUpdate(FIXED_DT);
            accumulator -= FIXED_DT;
        }

        // Remainder ratio alpha (for interpolating between previous and current physics states)
        float alpha = accumulator / FIXED_DT;

        BeginDrawing();
        ClearBackground(RAYWHITE);
        DrawText("Fixed Timestep Running", 20, 20, 20, DARKGRAY);
        DrawFPS(20, 50);
        EndDrawing();
    }

    CloseWindow();
    return 0;
}

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

  • 나선형 사망(Spiral of Death) 상한 설정: 창 제목 표시줄을 마우스로 드래그하거나 일시적인 시스템 렉이 발생하면 GetFrameTime()이 수 초까지 커질 수 있습니다. frameTime > 0.25f 클램핑이 없으면 while 루프가 수백 번 돌면서 다음 프레임을 더욱 지연시키는 악순환에 빠집니다.
  • 렌더링 보간(alpha)을 통한 미세 끊김(Jitter) 제거: 144Hz 모니터에서 60Hz 물리 루프를 돌리면 어떤 프레임은 물리 틱이 0번, 어떤 프레임은 1번 실행되어 시각적 떨림이 보일 수 있습니다. 각 엔티티의 직전 좌표(prevPos)와 현재 좌표(currPos)를 보관한 뒤 Vector2Lerp(prevPos, currPos, alpha)로 그리면 모든 주사율에서 부드럽게 표시됩니다.
  • 일회성 입력(IsKeyPressed) 누락 주의: IsKeyPressed()는 렌더링 프레임당 한 번만 true가 되므로, while (accumulator >= FIXED_DT) 내부에서 직접 호출하면 물리 틱이 0번 도는 프레임에서 입력이 유실되거나 2번 도는 프레임에서 중복 실행됩니다. 입력 폴링은 루프 바깥에서 먼저 수집해 플래그로 전달해야 합니다.
  • Clamp frameTime to Prevent the Spiral of Death: Dragging the OS window title bar or hitting a temporary stall can cause GetFrameTime() to return several seconds. Clamping frameTime to 0.25f prevents the inner while loop from running hundreds of catch-up ticks and freezing the application.
  • Eliminate Visual Stutter with Render Interpolation (alpha): Running a 60Hz physics tick on a 144Hz monitor executes 0 ticks on some render frames and 1 tick on others. Storing prevPos and currPos and drawing at Vector2Lerp(prevPos, currPos, alpha) produces smooth motion across all refresh rates.
  • Buffer Edge-Triggered Inputs Outside the Inner Loop: Because IsKeyPressed() is cleared once per render frame, polling it directly inside while (accumulator >= FIXED_DT) drops inputs on frames where the loop runs 0 times or triggers twice when it runs 2 times. Poll edge-triggered inputs before the while loop and consume latched flags on the first physics tick.

가변 주사율 렌더링과 고정 주사율 물리 업데이트를 누적기 루프로 분리하면, 60Hz 노트북부터 240Hz 게이밍 모니터까지 동일한 물리 법칙과 부드러운 화면 출력을 동시에 만족할 수 있습니다.

Decoupling variable-rate rendering from fixed-rate physics updates ensures identical gameplay mechanics across 60Hz laptops and 240Hz gaming monitors.

참고자료 & 관련 링크