0

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?

Caio B
  • 25
  • 1
  • 3
  • 2
    It's unclear to me what you want. Are you saying you only want to update xEnemy or yEnemy _once_ per check? Or exclusively update only one of xEnemy or yEnemy per check? Update the question with an [edit]. But, in general, explain to yourself and us in plain language what you expect to happen in the game on every movement or check. Then the code will be in context. –  Nov 01 '18 at 19:53
  • I want the enemy to follow the player using only the X or Y axis (no diagonals). The code works fine for that, the enemy follows the character all the way through the axis he's moving in, then changes to the opposite one. The problem is the flicker that sometimes happens when changing it's axis. – Caio B Nov 02 '18 at 16:08

1 Answers1

0

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;
      }
   }
cleblanc
  • 3,678
  • 1
  • 13
  • 16
  • Thank you for answering! I've tried that before. The problem is that the enemy bitmap will never move towards the opposite axis unless the player character manages to turn the relative distance bigger than the other axis' (if they're on the same x position, for example, their distance equals zero, the minimum possible, so no movement) – Caio B Nov 02 '18 at 02:26