I am trying to move an object to a random location when something happens.
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 ?
asked Jan 27, 2010 at 07:20 PM
In general, use the Start() function to perform actions that you only want to occur once, when the object first appears. Eg:
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 :)