0
\$\begingroup\$

In the Hierarchy I have a Cube and the script is attached to the cube. And I also have in the Hierarchy two spheres as waypoints.

public class WP : MonoBehaviour
{
    public Transform[] waypoints;
    public float movingSpeed;

    GameObject[] allLines;
    GameObject[] duplicatedPrefabs;

    private void Start()
    {
        allLines = GameObject.FindGameObjectsWithTag("FrameLine");

        DuplicatePrefabEffects(allLines.Length);
        duplicatedPrefabs = GameObject.FindGameObjectsWithTag("Duplicated Prefab");
    }

    private void DuplicatePrefabEffects(int duplicationNumber)
    {
        for (int i = 0; i < duplicationNumber; i++)
        {
            var go = Instantiate(prefabEffect);
            go.tag = "Duplicated Prefab";
            go.name = "Duplicated Prefab";
        }
    }

    private void MoveDuplicated()
    {
        for (int i = 0; i < duplicatedPrefabs.Length; i++)
        {
           duplicatedPrefabs[i].transform.position = Vector3.Lerp(pointA.position, pointB.position, movingSpeed *Time.deltaTime);
        }
    }

    void Update()
    {
     MoveDuplicated();
    }
}

The duplicatedPrefabs are moving very very fast no matter what value I put for movingSpeed and then they are all stuck in the second waypoint and seems like moving on very specific small area on the second waypoint.

What I want to do is to move them smooth slowly between the two waypoints and with random speed range from each object. For example one will move at speed 1 the other on speed 20 third on speed 2.

\$\endgroup\$
3
\$\begingroup\$

It looks like you're trying to use Lerp as though it were MoveTowards. Lerp just picks a point between two extremes, it doesn't automatically move that picked point unless you change its inputs.

Try this instead:

for (int i = 0; i < duplicatedPrefabs.Length; i++)
{
   duplicatedPrefabs[i].transform.position = Vector3.MoveTowards(
                duplicatedPrefabs[i].transform.position,
                pointB.position,
                movementSpeeds[i] * Time.deltaTime
            );
}

Two things to note here:

  1. This moves the prefabs toward pointB from wherever they happen to be. Make sure you're spawning them at pointA so they start from the right place.

  2. This assumes a parallel array of movement speeds for each object that you've populated in advance, using something like Random.Range()

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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