You just have to make the other characters do exactly the same things the player-character does, but with a delay. So you have to create a script which records the actions of the player and then allows to retrieve the player's position X steps ago.
The C# standard already has the ideal data-structure for that, the Queue
. It allows you to create a first-in-first-out buffer of a fixed size where you can add elements to the end with Enqueue and remove elements from the beginning with Dequeue.
using System.Collections.Generic;
using UnityEngine;
public class FollowTheLeader : MonoBehaviour {
public GameObject leader; // the game object to follow - assign in inspector
public int steps; // number of steps to stay behind - assign in inspector
private Queue<Vector3> record = new Queue<Vector3>();
private Vector3 lastRecord;
void FixedUpdate() {
// record position of leader
record.Enqueue(leader.transform.position);
// remove last position from the record and use it for our own
if (record.Count > steps) {
this.transform.position = record.Dequeue();
}
}
}
This script is just a very simple proof-of-concept. It only copies the position, but you likely also want it to copy the player's rotation (or at least the direction it faces), what action it performs (walking, jumping, etc.) and also handle a couple other edge cases specific to your game. So you will likely need to record more in the queue than just a Vector3. If that is the case, create your own struct
with all the data you need and use that as the type of your queue.
It might get even more complicated if you don't just want the followers to move to the exact position of the player but keep some respect distance. For example, if the player jumps, you might not want the follower to stop mid-air. You might want them to wait until the player completed the jump. So you might want to use record.Peek()
to look at the next action in the queue without removing it and if you find that it is a "start to jump" action, then don't dequeue it while the leader is still in the air.
And then there is the question: Do you want the follower to be able to fail? You could give it its own collision physics, but then you will have situations where the follower is unable to do what the leader did (like jumping on a moving platform which isn't there anymore). What happens now? You could do it like Sonic 2 did and have the follower just try anyway, die, and then return after a while. But that kind of slapstick humor might not be appropriate for the setting of every game. If you want the followers to act more competently, then you will have to implement 2d platformer pathfinding. But this can get really complicated, especially with changing environments.