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?
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.