0
\$\begingroup\$

Now all the moving objects are moving like a group to the same target. I need them to move to the same target but with a delay between them.

The first object start moving to the target after X seconds the second object start moving to the target then the third and so on they all should move to the first target but with a delay between the moving start.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveToTarget : MonoBehaviour
{
    public AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, 0.0f, 1.0f, 1.0f);
    public List<Transform> targets = new List<Transform>();
    public List<Transform> objectsToMove = new List<Transform>();
    public float duration;
    public bool moveToSameTarget = false;

    private float t;
    private List<Vector3> originPositions = new List<Vector3>();

    // Start is called before the first frame update
    void Start()
    {
        t = 0.0f;
        curve.postWrapMode = WrapMode.Once;

        for (int i = 0; i < objectsToMove.Count; i++)
        {
            originPositions.Add(objectsToMove[i].transform.position);
        }
    }

    // Update is called once per frame
    void Update()
    {
        t += Time.deltaTime;
        float s = t / duration;

        for (int i = 0; i < objectsToMove.Count; i++)
        {
            objectsToMove[i].position = Vector3.Lerp(originPositions[i], targets[0].position, curve.Evaluate(s));
        }
    }
}
\$\endgroup\$
0
0
\$\begingroup\$

Currently your t is evaluated the same for all your objects. If they should arrive at different times at your destination, they need their own t or at least know the delay. Without changing too much of your logic, you could assign a negative startTime to future objects and apply it only once it turns positive.

private List<float> startTime = new List<float>();
public float delay = 0.75f;

void Start() {
        t = 0f;
        curve.postWrapMode = WrapMode.Once;
        for (int i = 0; i < objectsToMove.Count; i++) {
            startTime.Add(-1 * i * delay);
            originPositions.Add(objectsToMove[i].transform.position);
        }
    }

    void Update() {
        t += Time.deltaTime;
        for (int i = 0; i < objectsToMove.Count; i++) {
            float s = (t + startTime[i]) / duration;
            if (s > 0) {
                objectsToMove[i].position = Vector3.Lerp(originPositions[i], targets[0].position, curve.Evaluate(s));
            }
        }
    }
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .