# How do I make a character follow behind another?

I'm creating a game in C++ using OpenGL. I want to add a character into my game who, after meeting the main player, follows the player around. The follower should position themselves directly behind the player, moving when the player does to stay in the correct position:

How can I accomplish this?

• How does the player move? Do they always face one direction? Do you want the NPC to follow the same path as the player, or always be directly behind the player? Does the player and/or NPC have to navigate obstacles? – mouseas Apr 25 '14 at 22:53
• The player does have to navigate obstacles but the follower doesn't. The player moves forward by following the cursor but can turn at any angle necessary. I don't mind what path the follower takes, I just require them to follow the player. – edwoollard Apr 25 '14 at 23:02

There are several options for this.

• Keep a queue of a fixed number of past positions of the player character to which you append only whenever the player moves. Always place the NPC at the oldest position in that queue. That will look as if the NPC mimics past moves of the player-character. There will be no way for the PC to shake off the NPC, because it will always be behind even when physically impossible.
• Calculate the position behind the player based on the players coordinates and direction. Then navigate the NPC to that location using a stock route-finding algorithm like A*. This will look much more natural because the NPC can fall behind, but they might get stuck when the route to the player-character gets blocked for some reason.

This will demonstrate how to create a dynamic list of positions the AI could move towards while following the player without mimicking the players movements or using a path-finding algorithm.

Assumptions:

• We need to know if the player could be reached in a straight line of movement (another question).
• We need to be able to tell the AI to perhaps look at the player when it's not moving towards her. Otherwise the AI needs to look towards where the AI itself is going.
• We should define some distance that we consider close enough (we don't want the follower to walk "inside" the player, that may be uncomfortable for both of them.
• We need to remember the last position of the player (where she was in the previous frame).

What we'll do:

We'll maintain a list of a minimal amount of points needed to follow the player (we'll use it to find the shortest path towards her).

Pseudo code:

// The player will leave a dynamic trail of cookie crumbs
// If the player is reachable in a straight line then the only coordinate we need is
// her current position
if (player.pos ().isReachableFrom (ai.getPos ()){
checkPointList.clearList ();