Wednesday, October 24, 2018

unity - How can I move number of objects between two points with random speed?


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.



Answer



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()




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...