cgame-boy-advance

How do I remove a single life per collision of two 2D objects?


I am programming a game for fun and to get more familiar with C and GBA mode 3. Though, I have run into an issue.

I have these two blocks on the screen, one is the good guy, the other is the bad guy. When the good guy collides with the bad guy its supposed to remove a life. That is where the problem comes in.

I have this within a while loop that runs the game:

    if (plyr_row < enemy_row + enemy_size && plyr_ row 
    + plyr_size > enemy_row && plyr_col < enemy_col + enemy_size
    && plyr_size + plyr_col > enemy_col) 
    {
      lives--;
    }

The lives do go down, but a lot of lives are taken away while the player is making contact with the enemy. In other words, during contact, the lives drop really fast and I just want to remove one for each time they collide, how can I accomplish that?


Solution

  • You have to use a flag to remember, if a collision is currently happening or not. Something like:

    int in_collision = 0; // global flag, initialized to 0 once at start
    
    ...
    
    if (plyr_row < enemy_row + enemy_size &&
        plyr_row + plyr_size > enemy_row &&
        plyr_col < enemy_col + enemy_size &&
        plyr_size + plyr_col > enemy_col) {
       if (!in_collision) {
           in_collision = 1;
           lives--;
       }
    } else {
       in_collision = 0;
    }
    

    Now, the running collision must stop before another life will be removed on the following collision.