# moving object to a random location

Hi there,

I am trying to move an object to a random location when something happens.

``````    transform.eulerAngles=Vector3(0,targetRot,0);
moveDirection = Vector3(targetX,0,targetZ);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *=runSpeed;
transform.Translate(moveDirection*Time.deltaTime);

``````

this makes gets called in the Update function and of course the objects gets those random targetX,targetZ and targetRot variables recreated every frame. This makes the object go into a seizure.

What I would like to do is, create those random values only once and make the object go to that location.

There is also the problem of heading the right direction, random value of targetRot does not necessarily point to the target X and Z. I guess I'll need some math there as well?

so the question are:

-how to create those variables once even though the function is called every frame? -how to set the euler angle of the object correctly to make it face the right direction ?

Thank you

In general, use the Start() function to perform actions that you only want to occur once, when the object first appears. Eg:

``````var target : Vector3;

function Start() {
target = Random.insideUnitSphere * 5;
}

function Update() {
transform.Translate((target-transform.position)*Time.deltaTime);
}

``````

However in your situation, you might want to be able to pick a new random position at any given time, so it might be better to move the random target function, and the code which controls initialisation of the direction to a custom function. You can then call the custom function both in Start() and elsewhere - for instance, in OnMouseUp() or OnCollisionEnter() for example.

In the example below, I'm using Transform.LookAt to make the object face in the direction of the target. I'm also using a different method of moving an object, which calculates the current position by Lerping between the start position and the target position. All good stuff to look up :)

``````var target : Vector3;
var target : Vector3;
var timeStarted : float;

function Start() {
PickRandomTarget();
}

function PickRandomTarget() {
target = Random.insideUnitSphere * 5;
transform.LookAt(target);
timeStarted = Time.time;
startPosition = transform.position;
}

function Update() {
var i : float = (Time.time-timeStarted);
transform.position = Vector3.Lerp(startPosition, target, i );
}

// pick a new target if clicked
function OnMouseUp() {
PickRandomTarget();
}

``````