Remove Ads

Share on Facebook Share on Twitter

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Allegro: Sprite Animations
#1
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.
[code]
#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);
if(!Sprite)
{
allegro_message("No Sprite.bmp in this directory...");
return 0;
}

while (!key [KEY_ESC])
{
logic();

// Always draw last
draw();

}
// End of Game Loop
clear(screen);
destroy_bitmap(Sprite);
destroy_bitmap(Buffer);
return 0;
}
END_OF_MAIN()

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

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

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

Thanks alot!
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)