1

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.

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;

}}

Here is the routes script i don't think you will need but will include this

public class Route : MonoBehaviour{
[SerializeField]
private Transform[] controlPoints;

private Vector2 gizmosPos;

private void OnDrawGizmos()
{
    for(float t = 0; t <= 1; t += 0.05f)
    {
        gizmosPos = Mathf.Pow(1 - t, 3) * controlPoints[0].position +
            3 * Mathf.Pow(1 - t, 2) * t * controlPoints[1].position +
            3 * (1 - t) * Mathf.Pow(t, 2) * controlPoints[2].position +
            Mathf.Pow(t, 3) * controlPoints[3].position;

        Gizmos.DrawSphere(gizmosPos, 0.25f);
    }

    Gizmos.DrawLine(new Vector2(controlPoints[0].position.x, controlPoints[0].position.y),
        new Vector2(controlPoints[1].position.x, controlPoints[1].position.y));

    Gizmos.DrawLine(new Vector2(controlPoints[2].position.x, controlPoints[2].position.y),
       new Vector2(controlPoints[3].position.x, controlPoints[3].position.y));
}}

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

10
  • Does answers.unity.com/questions/894796/… not help? Or youtube.com/watch?v=fKWTpi70a_E? (mute it because the music is literally the worst) Jul 12, 2019 at 17:18
  • Hi, no unfortunately they do not cover what it is im trying to implement,i have actually seen those links, i already have the functionality with one object following a bezier curve, i am needing multiple objects follow the same curve Jul 12, 2019 at 18:05
  • 1
    If I'm reading your code correctly, isn't every follower defined to use exactly the same values? E.g. if you build 10 of them, all 10 will move identically because they all start moving at the same time (I don't see a random X frame delay that you take into account in update()) and they all travel at the same speed (I don't see a randomization for that in start()). Jul 12, 2019 at 18:46
  • yes that is correct, this why i am asking for help to have objects follow the path in order Jul 13, 2019 at 7:55
  • @DavidMarsh Could you perhaps provide an example video of the current problem, I don't seem to understand the exact behavior you want to achieve. Thanks.
    – Hristo
    Jul 13, 2019 at 8:39

2 Answers 2

2
+50

I Know what you are trying to achieve and i do believe you can do this with an extra script without changing your current code.

Here i have made a new script called EnemyBehavior.

public class EnemyBehavior : MonoBehaviour{
public Path pathToFollow;

//PATH INFO
public int currentWayPointID = 0;

//speeds
public float speed = 2;
public float reachDistance = 0.4f;
public float rotationSpeed = 5f;

float distance; //DISTANCE TO NEXT PATH POINT

public bool useBezier = false;

//STATE MACHINES
public enum EnemyStates
{
    ON_PATH,        
    IDLE
}
public EnemyStates enemyState;

public int enemyID;

void Update()
{
    switch (enemyState)
    {
        case EnemyStates.ON_PATH:
            MoveOnThePath(pathToFollow);
            break;            
        case EnemyStates.IDLE:

            break;
    }
}

void MoveToFormation()
{
    //transform.position = Vector3.MoveTowards(transform.position, formation.gridList[enemyID], speed * Time.deltaTime);
    //if(Vector3.Distance(transform.position, formation.gridList[enemyID])<= 0.001f)
    {
        //transform.SetParent(formation.gameObject.transform);
        transform.eulerAngles = Vector3.zero;
        enemyState = EnemyStates.IDLE;
    }
}

void MoveOnThePath(Path path)
{
    if (useBezier)
    {
        //MOVING THE ENEMY
        distance = Vector3.Distance(path.bezierObjList[currentWayPointID], transform.position);
        transform.position = Vector3.MoveTowards(transform.position, path.bezierObjList[currentWayPointID], speed * Time.deltaTime);
        //ROTATION OF YOUR ENEMY
        var direction = path.bezierObjList[currentWayPointID] - transform.position;

        if (direction != Vector3.zero)
        {
            direction.z = 0;
            direction = direction.normalized;
            var rotation = Quaternion.LookRotation(direction);
            transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
        }
    }
    else
    {
        distance = Vector3.Distance(path.pathObjList[currentWayPointID].position, transform.position);
        transform.position = Vector3.MoveTowards(transform.position, path.pathObjList[currentWayPointID].position, speed * Time.deltaTime);

        //ROTATION OF ENEMY
        var direction = path.pathObjList[currentWayPointID].position - transform.position;

        if (direction != Vector3.zero)
        {
            direction.y = 0;
            direction = direction.normalized;
            var rotation = Quaternion.LookRotation(direction);
            transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
        }
    }        
}}

Attach this script to all the game objects that you intend to use the path and don't forget to assign the path on these in the inspector.

You may need to adjust the direction to suit your needs if it is a 2D game but this should work for you. Let me know how you get on and feel free to direct contact me.

2
  • 2
    Brilliant, works great after changing the direction to direction.x, all objects following along nicely i cannot thank you enough for helping, very kind Jul 15, 2019 at 9:00
  • Welcome glad to help :-)
    – mard dean
    Jul 15, 2019 at 9:05
0

How about this approach:

  1. Attach BezierCurve to all gameObject that need the behaviour. Don't keep any Parent-Child relationship.
  2. Prevent BezierCurve to follow/start automatically. Keep a bool to stop, in case you need.
  3. Create a new script BezierCurveBatch, attach to main(Parent) gameObject and have List<BezierCurve> contains reference of children. In same script, keep a float, let's say delayStartCurve to manage time between two BezierCurve start.
  4. In BezierCurveBatch, start the BezierCurve from List<BezierCurve> children after every delayStartCurve.

I have provided a demo script code. Not tested but it should work.

public class BezierCurve
{
    //Starts following bezier curve.
    public void StartFollow()
    {
        //some code here.
    }
}

public class BezierCurveBatch : MonoBehaviour
{
    [SerializeField]
    List<BezierCurve> m_lstChildren;

    [SerializeField]
    float m_delayStartCurve = 10;
    float m_timeLeftToStartNextChild = 0;

    bool m_isRunBatchCurve = false;

    /// <summary>
    /// Start batch follow after each interval.
    /// </summary>
    public void StartBatch()
    {
        m_isRunBatchCurve = true;
    }

    private void Update()
    {
        if (!m_isRunBatchCurve)
            return;

        m_timeLeftToStartNextChild -= Time.deltaTime;
        if (m_timeLeftToStartNextChild <= 0.0f)
        {
            if (m_lstChildren.Count > 0) //if we have children left.
            {
                BezierCurve l_bCurveToStart = m_lstChildren[0];     //Getting top object.
                m_lstChildren.RemoveAt(0);                          //removing top object.
                l_bCurveToStart.StartFollow();                      //Start follow bezier curve
                m_timeLeftToStartNextChild = m_delayStartCurve;     //resetting time.
            }

            if (m_lstChildren.Count == 0)       //After processing last object, check if need to continue for next object.
                m_isRunBatchCurve = false;
        }
    }
}
10
  • Will try this now and report back, appreciate the help Jul 9, 2019 at 9:22
  • Hi, struggling to implement this, do you have an example? also number 1. don't keep any parent child relationship but number 3 you say to attach to parent object? Jul 9, 2019 at 9:48
  • 1
    @DavidMarsh I have updated my answer with sample code.
    – MicroEyes
    Jul 9, 2019 at 10:21
  • The list and variables in the BezierCurveBatch do not seem to be showing when attached to parent object, even though they are serialised, only warning i see in console is...'BezierCurveBatch.m_lstChildren' is never assigned to, and will always have its default value null Jul 9, 2019 at 10:36
  • 1
    @DavidMarsh. Its because i didn't know whether your BezierCurve class is derived from Monobehaviour or not. * If your BezierCurve is derived from Monobehaviour, then it was already serializing in editor and you just need to drag and drop the references in List. * If your BezierCurve is not derived from Monobehaviour, then add [System.Serializable] attribute on your class BezierCurve. Again my sample code was just for logic reference.
    – MicroEyes
    Jul 9, 2019 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.