Caio B
Caio B

Reputation: 25

Flickering when a bitmap follows another in Allegro

I'm developing a 2D game using C with Allegro 5. Right now, I'm coding the movement of an in-game enemy, a bitmap that follows the player (coordinates X and Y). While it works perfectly for the X axis, it often fails to go towards the player at the Y axis, having the bitmap flicker instead of move.

Here is the code I am using:

if(*xEnemy < *x){
    *xEnemy += 3;
}else if(*xEnemy > *x){
    *xEnemy -= 3;
}else if(*yEnemy < *y){
    *yEnemy += 3;
}else if (*yEnemy > *y){
    *yEnemy -= 3;
}

It would work just fine if I used ifs instead of else ifs, however, the enemy would walk on diagonal paths, and that is not something I'm planning for the game. It's clear that the problem lies with the elses, so what is a working alternative for them?

Upvotes: 0

Views: 83

Answers (1)

cleblanc
cleblanc

Reputation: 3688

Can you look at the absolute value of the relative distance to decide to move in the x or y direction, for example;

xAbs = abs(*xEnemy - *x);
yAbs = abs(*yEnemy - *y);

   if (xAbs < yAbs)
   {
      // Move in the x direction since we're closer there
      if(*xEnemy < *x){
          *xEnemy += 3;
      } else if(*xEnemy > *x){
          *xEnemy -= 3;
      }
   }
   else
   {
      // Move in the y direction
      if(*yEnemy < *y){
          *yEnemy += 3;
      } else if (*yEnemy > *y){
          *yEnemy -= 3;
      }
   }

Upvotes: 0

Related Questions