[Allegro] timers & animation

Started by
1 comment, last by Escarab 16 years, 1 month ago
I'm newbie in allegro and i've a reasonable knowledge on c++. I'm making a class to encapsulate an animated sprite, and a bunch of problems I can't solve alone have emerged. I hope someone in here know the answers. -Someone can explain me why the variables used on the function called by the timer must be locked and volatile? Can I use volatile objects of my own classes? -How to animate Sprites using timers and double buffer at the same time without calling a function inside the timer's function(i.e. using a variable incremented inside the timer's function)? Can you give me an example? -Do allegro's timer makes a new thread? So, basically, i wanna do animated sprites using allegro, someone can help?
Advertisement
Variables that are called in timers must be locked if you run your code on DOS or Mac OS 9. You can safely ignore it. The reason why it was important on those operating systems is because timers were implemented as interrupts. It's no longer relevant, although it won't hurt to add those macros.

Under all other operating systems, Allegro timers are just threads. From the manual:
Quote:
Under other platforms, they are usually implemented using threads, which run parallel to the main thread. Therefore timer callbacks on such platforms will not block the main thread when called, so you may need to use appropriate synchronisation devices (eg. mutexes, semaphores, etc.) when accessing data that is shared by a callback and the main thread. (Currently Allegro does not provide such devices.)

Generally speaking the only usefulness of an Allegro timer is to increment a tick variable and monitor that in your main section. The tick variable must be volatile or else the compiler may optimize it away when you use it elsewhere because it won't know that the value has the potential to change.

I suggest that you look at the examples that come with the Allegro source. There are some basic examples. The easiest way to do this is to just have a single tick variable that is incremented 60 (or 120, etc) times a second. Then you do this:

while (playing){  while (ticker) // ticker will be incremented 60 times per second by your timer  {    do_logic();    draw_gfx = 1;    ticker--;  }  if (graw_gfx)  {    do_gfx();    draw_gfx = 0;  }  else    rest(1); // try not to burn up 99% of CPU}


Inside your do_logic() routine, you might do something like this:
if (my_sprite.ticks++ > my_sprite.ticksPerFrame){  my_sprite.frame++;  my_sprite.ticks = 0;}


Then when you draw the sprite in the do_gfx() routine, you look at which frame it is currently on and draw accordingly.
Thanks konForce, you really helped me out!

This topic is closed to new replies.

Advertisement