I’ve got several GO’s on a playing field. They are all neatly spread out at first. I’ve got it so that each generate a random position and translate to them, but the position they translate to are al very close to each other.
Here’s what I’m doing:
var maxDistance : int = 6.0;
var minDistance : int = 2.0;
var newPos : Vector3;
function Update ()
{
UpdatePosition();
//Debug.DrawLine(transform.position, newPos, Color.red);
}
// THIS FUNCTION IS CALLED ONCE FOR EACH GO, EACH TIME TO NEED TO MOVE (and when GamePlayScript.OpponentsShouldBeMoving is set to true)
// THIS IS CALLED FROM AN ANOTHER SCRIPT, LIKE THIS:
/*
GamePlayScript.OpponentsShouldBeMoving = true;
var opponents = FindObjectsOfType(MoveOpponent);
for( var opponent in opponents )
{
opponent.GenerateRandomPos();
}
*/
function GenerateRandomPos()
{
newPos = Random.onUnitSphere * Random.Range( minDistance, maxDistance );
newPos.y = originalPos.y;
}
function UpdatePosition()
{
if(GamePlayScript.OpponentsShouldBeMoving)
{
//...
else
{
time = 0.0;
// Translate to the original position
while(true)
{
time += Time.deltaTime;
transform.position = Vector3.Lerp (transform.position, newPos, Mathf.Clamp01 (time));
yield;
if ( time > 1.0 ) break;
}
}
//...
}
}
If I understand correctly, you have a group of dudes who repeatedly move by Random.onUnitSphere units, and they tend not to wander far from their starting positions?
That has nothing to do with how random Random.onUnitSphere is, it’s just statistics - the more times you get a random choice where all possibilities are equally likely, the less likely you are to actually end up very far from the starting point. Flip a coin a thousand times, you’ll get around 500 heads.
If you DID want them to spread out more, you have to bias the odds somehow. You can use boids-like logic to “push” them all away from the center of the herd or away from other nearby agents. You can have a constant “weight” that is randomized at the start but not every time the agent moves, and when they move you move them by constantRandomVector*0.1 + Random.onUnitSphere.
One possibility is that, You’re calling a coroutine every frame, and so you end up having dozens of these coroutines running alongside each other. this is a Bad Thing, and it’s also exactly why you’re not allowed to write Update() as a coroutine. Instead of calling UpdatePosition from Update, you should call it when the pos is randomized.
Also, looking once more at your code, the reason they’re converging is because you’re starting at the origin instead of at the position of at transform.position. add transform.position to Random.onUnitSphere when you generate it.