Search code examples
c++imagebackgroundallegroallegro5

Image over another image in allegro5 (C++)


I have a problem with adding a background in my game. My code looks like that:

while (true)
{
    al_draw_bitmap(background, 0, 0, NULL);
    al_flip_display();
    some code(...);
    al_draw_bitmap(snake,0,0,NULL);
    /*drawing my snake's tail*/
    al_clear_to_color(al_map_rgb(0,0,0));
    al_draw_bitmap(apple,0,0,NULL);
    al_flip_display();
}

And I have visible an apple and a black screen most of the time. I've been changing order of some lines in code and none of these combination worked (best case was when I had visible snake and background but there was no apple). Before adding a background, my snake's tail sometimes disappered, but it wasn't very visible, and except that, everything seemed to be okay. Anyone knows how to add a background properly? Or maybe it's fault of my computer?


Solution

  • Once per draw loop, you should:

    1. clear the display
    2. draw your background
    3. draw bitmaps on top of the background
    4. flip the display

    For example:

    al_clear_to_color(al_map_rgb(0,0,0));
    al_draw_bitmap(background, 0, 0, NULL);
    al_draw_bitmap(apple,0,0,NULL);
    al_draw_bitmap(snake,0,0,NULL);
    al_flip_display();
    

    Note that you should only call al_flip_display once per draw loop, after you have drawn everything for that loop. al_clear_to_color should be called first as it will wipe out everything you have drawn. In the example you gave, you are drawing your apple and snake to the same location, so I wouldn't be suprised if one is blocking part of the other.

    Also, you probably don't want to stick your draw loop in a while(true) as the framerate will be unconstrained. That is, it will run as fast as it is allowed, and the framerate won't be consistent. The typical approach is to use an event-driven draw loop.