Search code examples
cmultithreadinggame-loopallegro5

Allegro 5 game: game loop that runs at constant speed?


What is the best way to code a game loop in Allegro 5 that always runs at the same speed, and that properly separates drawing logic from update logic? Should I use threads or not? Should I make use of the new Allegro event system?


Solution

  • Taken from the allegro wiki:

    al_install_timer(1.0 / FPS);
    
    ...
    
    while (1) {
            al_wait_for_event(queue, &event);
    
            /* handle input events */
    
            if (event.type == ALLEGRO_EVENT_TIMER) {
                    handle_game_tick();
                    need_redraw = true;
            }
    
            if (need_redraw && al_event_queue_is_empty(queue)) {
                    render_last_frame();
                    need_redraw = false;
            }
    }
    

    If you want frame skipping, skip the render_last_frame() command whenever you detect that you are lagging behind in frames (e.g. by using the al_current_time() function).