Computer Tech

Full Version: Allegro: Sprite Animations
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Now we're getting to some fun stuff.
For this tutorial you should use the image in the .zip at the bottom.

Notice the sprites are evenly spaced apart on the image. This is called a sprite sheet, and it's the easiest way to have a sprite animation.

To achieve the animation is rather simple if the images are the same distance apart.
We'll use the masked_blit() function for this.

masked_blit(Bitmap_to_draw, where_to_draw, source_x, source_y, destination_x, destination_y, width of blit, height of blit)

Big function right?

The individual sprites on that image are 32x32, so remember that.

Since the image is 96x128 I define the coordinates below. I'll let the code speak for itself.
#include <allegro.h>
#define down 0
#define left 32
#define right 64

BITMAP *Buffer = NULL;
BITMAP *Sprite = NULL;

void draw();
void logic();

short x = 0;
short y = 350;

short Sprite_X = left;
short Sprite_Y = down;

int main ()
// You always want to initialize everything before you do things in your program
allegro_init ();
install_keyboard ();
set_color_depth (32);
set_gfx_mode (GFX_AUTODETECT, 640, 480, 0, 0);//Screen resolution

Buffer = create_bitmap (SCREEN_W, SCREEN_H);
Sprite = load_bitmap ("Sprite.bmp", NULL);
allegro_message("No Sprite.bmp in this directory...");
return 0;

while (!key [KEY_ESC])

// Always draw last

// End of Game Loop
return 0;

void draw()
    masked_blit (Sprite, Buffer, Sprite_X, Sprite_Y, x, y, 32, 32);
    draw_sprite(screen, Buffer, 0, 0);
    rest (50);

void logic()
    Sprite_X += 32;//Sprite walk animation
    Sprite_Y = down;
    if (key[KEY_RIGHT])
    x += 5;
    Sprite_Y = right;
    else if (key[KEY_LEFT])
    x -= 5;
    Sprite_Y = left;
    Sprite_X = left;
    if (Sprite_X > right)
    Sprite_X = down;
Thanks man, that helped me a lot on understanding the basics of using a sprite sheet.

Keep up the good job!!
Really nice sample to get understand what teacher taught in class!

Thanks alot!
Reference URL's