- Home /
Semi-Controlled Array Randomization
Essentially, what this javascript does is choose a random Transform from an array and moves the camera towards the transform. Then, when the camera collides with one of the Transforms, it randomly chooses a new one and moves towards it. Rinse and Repeat.
However, i am coming across an issue where the random generator will choose the new target to be the same as the old target, which causes the loop to quit itself. What do I need to do to make the old and new targets to be different each time?
//Array of Possible Camera Target Locations and Current Target
var movTargets : Transform[] = new Transform[6];
var currentTarget : Transform;
function OnTriggerEnter (Collider) {
PickRandomTarget();
}
function Update () {
transform.LookAt(target);
MoveToTarget();
}
function PickRandomTarget () {
// set currentTarget to a new target from the movTargets[] array
currentTarget = movTargets[Random.Range(0, movTargets.Length)];
Debug.Log(currentTarget);
}
function MoveToTarget () {
//Automatically Moves Camera to currentTarget
transform.position = Vector3.MoveTowards(transform.position, currentTarget.position, speed * Time.deltaTime);
}
I am very inexperienced with javascript (and programming languages in general), so any help provided will be greatly appreciated.
Answer by whydoidoit · Jun 29, 2012 at 02:33 PM
try this:
function PickRandomTarget () {
// set currentTarget to a new target from the movTargets[] array
var newTarget : Transform;
do
{
newTarget = movTargets[Random.Range(0, movTargets.Length)];
} while((newTarget.position - currentTarget.position).sqlMagnitude < 1);
currentTarget = newTarget;
Debug.Log(currentTarget);
}