Allegro 5游戏:游戏循环以恒定速度运行?

时间:2009-07-31 11:31:56

标签: c multithreading game-loop allegro5

在Allegro 5中编写游戏循环的最佳方法是什么?它始终以相同的速度运行,并且正确地将绘图逻辑与更新逻辑分开?我应该使用线程吗?我应该使用新的Allegro事件系统吗?

2 个答案:

答案 0 :(得分:3)

取自快板维基:

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;
        }
}

如果要跳帧,请在检测到落后于帧时跳过render_last_frame()命令(例如,使用al_current_time()函数)。

答案 1 :(得分:3)

Here是Allefant答案的更完整版本(按照链接进行详细的逐行说明):

#include <stdio.h>
#include <allegro5/allegro.h>

const float FPS = 60;

int main(int argc, char **argv)
{
   ALLEGRO_DISPLAY *display = NULL;
   ALLEGRO_EVENT_QUEUE *event_queue = NULL;
   ALLEGRO_TIMER *timer = NULL;
   bool redraw = true;

   if(!al_init()) {
      fprintf(stderr, "failed to initialize allegro!\n");
      return -1;
   }

   timer = al_create_timer(1.0 / FPS);
   if(!timer) {
      fprintf(stderr, "failed to create timer!\n");
      return -1;
   }

   display = al_create_display(640, 480);
   if(!display) {
      fprintf(stderr, "failed to create display!\n");
      al_destroy_timer(timer);
      return -1;
   }

   event_queue = al_create_event_queue();
   if(!event_queue) {
      fprintf(stderr, "failed to create event_queue!\n");
      al_destroy_display(display);
      al_destroy_timer(timer);
      return -1;
   }

   al_register_event_source(event_queue, al_get_display_event_source(display));

   al_register_event_source(event_queue, al_get_timer_event_source(timer));

   al_clear_to_color(al_map_rgb(0,0,0));

   al_flip_display();

   al_start_timer(timer);

   while(1)
   {
      ALLEGRO_EVENT ev;
      al_wait_for_event(event_queue, &ev);

      if(ev.type == ALLEGRO_EVENT_TIMER) {
         redraw = true;
      }
      else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
         break;
      }

      if(redraw && al_event_queue_is_empty(event_queue)) {
         redraw = false;
         al_clear_to_color(al_map_rgb(0,0,0));
         al_flip_display();
      }
   }

   al_destroy_timer(timer);
   al_destroy_display(display);
   al_destroy_event_queue(event_queue);

   return 0;
}