Path creation
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 Sebastian Lague's path creation tool, 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();
}
After that we assign the position.
private void AssignPosition()
{
if (GetComponentInParent<River>())
pathCreator = GetComponentInParent<River>().pathCreator;
pathLength = pathCreator.path.length;
startPosition = Random.Range(0f, pathLength);
distanceTravelled = startPosition;
pathOffset = Random.Range(minPathOffset, maxPathOffset);
speed = Random.Range(minSpeed, maxSpeed);
Vector3 pathPostion = pathCreator.path.GetPointAtDistance(startPosition, endOfPathInstruction);
transform.position = pathPostion;
}
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.
protected override void Update()
{
if (pathCreator != null)
{
distanceTravelled += speed * Time.deltaTime;
Vector3 pathPostion = pathCreator.path.GetPointAtDistance(distanceTravelled, endOfPathInstruction);
Vector3 pathNormal = pathCreator.path.GetNormalAtDistance(distanceTravelled, endOfPathInstruction);
transform.position = pathPostion + pathNormal * pathOffset;
transform.rotation = pathCreator.path.GetRotationAtDistance(distanceTravelled, endOfPathInstruction)*randomRotation;
}
}
The end result

Last updated
Was this helpful?