I was tasked with making a tool that could be used to make a custom path that would allow other objects to follow it. I started this task by doing a bit of research about the subject. I came to the conclusion that I could either write my own path creator, find a path creator online or lerp objects from point to point as I did before:
I decided to download , the asset came with an example scene where an object is following a path.
The Code
I started out with spawning a bunch of objects that will later follow the path. I did this with the help of an objectpooler script that I wrote earlier.
public class River : MonoBehaviour
{
private ObjectPooler objectPooler;
private int amountOfRiverBalls = 75;
private int amountOfElastics = 75;
public PathCreator pathCreator;
[SerializeField]
private Transform riverElasticsContainer;
[SerializeField]
private Transform riverBallsContainer;
void Start()
{
objectPooler = ObjectPooler.Instance;
for (int i = 0; i < amountOfRiverBalls; i++)
{
objectPooler.SpawnFromPool("RiverBalls", transform.position, transform.rotation, riverBallsContainer);
}
for (int i = 0; i < amountOfElastics; i++)
{
objectPooler.SpawnFromPool("RiverElastics", transform.position, transform.rotation, riverElasticsContainer);
}
}
}
After I had a bunch of objects to populate the path I needed to place them in different places in the river path. I made a script for each object that travels along the river path called RiverPathFollower. The script will place the travelers in a random position on the river and then move them over the path.
First we call OnObjectSpawn when we enable an object from the pool.
public void OnObjectSpawn()
{
AssignPosition();
AssignRotation();
}
And here we update the position and rotation accordingly, we do that by updating the distanceTravelled variable that keeps track of how far along the path the follower is.