Follow a character only if they are close

Started by DiegoHolt, Sat 19/04/2025 00:32:07

Previous topic - Next topic

DiegoHolt

Hello community, I'm wondering what would be the best way for a character to chase the player but only if the player is near enough. In this case, this character is constantly walking and I need it to start chasing the player when they meet certain distance. I'm trying with coordinates calculations in the room's repeat_execute but things aren't working the way I was expecting.

Any help would be greatly appreciated, since I couldn't find any past topics about this.

Crimson Wizard

Please post the code that you are using, then it will be possible to tell what you are doing wrong.

Khris

Here's how to get the perspective corrected distance in pixels between two characters:

Code: ags
int DistanceFrom(this Character*, Character* other) {
  float dx = IntToFloat(this.x - other.x), dy = IntToFloat(this.y - other.y) * 1.5; // account for foreshortening
  return FloatToInt(Maths.Sqrt(dx * dx + dy * dy), eRoundNearest);
}

I'm assuming the main issue is that you're calling the FollowCharacter command more than once or something like that.
Code: ags
bool enemy_is_following;

function Room_RepExec() {
  if (!enemy_is_following && cEnemy.DistanceFrom(player) < 50) {
    cEnemy.FollowCharacter(player);
    enemy_is_following = true;
  }
}

And like CW says, please always post your own attempt; this is helpful for us because among other things we can judge how much assistance you need based on what you tried.

DiegoHolt

Thanks Khris, I'll try that later. Sorry for not posting the code, but I didn't have any. I deleted it and carried on with other issues of the game.

SMF spam blocked by CleanTalk