- Home /
Infinite random movement
I have a box area with some number of spheres (currently it is 20) inside this box. Each sphere is instantiate in random starting position inside this box.
For each sphere, I am trying to achieve this behavior:
Each sphere chooses some random position inside the box.
Goes to this position.
Repeat
In addition, when sphere hits another sphere, it also chooses a new position.
My code for spheres looks like this:
public Vector3 destination;
void DestinationChange () {
destination = new Vector3 (
Random.Range (xMin, xMax),
Random.Range(yMin, yMax),
Random.Range (zMin, zMax)
);
}
void Start () {
DestinationChange ();
}
void Update () {
if (Vector3.Distance (transform.position, destination) < 1) {
DestinationChange ();
}
transform.position = Vector3.MoveTowards(
transform.position, destination, Time.deltaTime * speed
);
}
void OnCollisionExit (Collision collision) {
DestinationChange ();
}
But it does not work good. After few seconds and few collisions,
some spheres just spin and slowly fly away without try to go to desired destination or another just stay in some place and oscilate between two very close positions far away from desired location.
What am I doing wrong?
Comment