- Home /
How to make game objects follow a path in order in Unity along a bezier curve
I have a single Object moving along a Bezier Curve but i have multiple objects that need to follow this path in order but they all follow at the same time.The object is a snake type enemy in a space shooter game.
I have so far tried to make all objects children but in doing this they remain in a straight line to the parent when follow the Bezier Curve. I have also made all objects separate and attached the Bezier Script to these so they all follow the same route and this works but only they follow the same path at the same time.
I think what i need to do is have each object not be a child object and all have the script attached to follow the route but also have a delayed time before it follows along the path but not sure how to go about this. I was thinking this might need to be done in a separate script because in the bezier curve script it is set so the object starts again at the beginning of the route once reaches the end
public class BezierFollow : MonoBehaviour
{
[SerializeField]
private Transform[] routes;
private int routeToGo;
private float tParam;
private Vector2 enemyPosition;
[SerializeField]
public float speedModifier = 0.5f;
private bool coroutineAloud;
// Start is called before the first frame update
void Start()
{
routeToGo = 0;
tParam = 0f;
//speedModifier = 0.5f;
coroutineAloud = true;
}
// Update is called once per frame
void Update()
{
if (coroutineAloud)
{
StartCoroutine(GoByTheRouteRoutine(routeToGo));
}
}
private IEnumerator GoByTheRouteRoutine(int routeNumber)
{
coroutineAloud = false;
Vector2 p0 = routes[routeNumber].GetChild(0).position;
Vector2 p1 = routes[routeNumber].GetChild(1).position;
Vector2 p2 = routes[routeNumber].GetChild(2).position;
Vector2 p3 = routes[routeNumber].GetChild(3).position;
while (tParam < 1)
{
tParam += Time.deltaTime * speedModifier;
enemyPosition = Mathf.Pow(1 - tParam, 3) * p0 +
3 * Mathf.Pow(1 - tParam, 2) * tParam * p1 +
3 * (1 - tParam) * Mathf.Pow(tParam, 2) * p2 +
Mathf.Pow(tParam, 3) * p3;
transform.position = enemyPosition;
yield return new WaitForEndOfFrame();
}
tParam = 0f;
routeToGo += 1;
if (routeToGo > routes.Length - 1)
routeToGo = 0;
coroutineAloud = true;
}
}
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Delay If statement in Update c# 2 Answers
Delay when loading new level :( 1 Answer
I want to create a pause in between spawning objects in a row 2 Answers