How do I get my team NPC to follow the player? | Game Maker Studio

I would like to have 4 teammate NPC's that would follow behind the Player. First off, I know how to get the movement and collisions working properly but getting the NPC's to follow the player is where I'm struggling.

This code checks if the player's x is greater than the x of the NPC so it can move right.

if obj_testPlayer.x > x - 34 { // want it to stop 34 pixels away from the players left
xspd += 3
} else {
xspd = 0;
}


Once the NPC is 34 pixels away from the Player it will stop, but when the player moves again, the NPC is stationary. Also, when I change this code to check if the player is on the left of NPC; The NPC won't move.

All I'm trying to do is get the NPC moving Horizontally when the player is on the right or the left side of the NPC but it's not working.

So technically, it already follows the player to the right, and you want it to move to the right and left side, while it stops if it gets too close?

In the given context, I think this is all you need:

if (obj_testPlayer.x > x + 34) { // want it to stop 34 pixels away from the players left
xspd += 3
} else if (obj_testPlayer.x < x - 34) {
xspd -= 3
}
else {
xspd = 0;
}


In such situations, I usually visualise the problem to understand what's going on, similair like this:

player.x <  -34    NPC    +34   player.x >
|         |      |      |       |

• I knew I was on the right track. I think my problem was that I used separate if statements. Thank you so much! May 6, 2020 at 8:03
• Ah yeah, if you're using seperate if statements to change the same variable, you may expect that the bottom if-statement will override it. Keep in mind to use else if statements in such situations. May 6, 2020 at 9:40