- Home /
multiple paths
In my game i want my character to move straight forward towards a tree automatically for 10 sec and he should perform some sort of action.I want after the player perform a serious of action he should return to the old position and again he should moving to the same place like wise 10 times he should reposition and move towards the place.I tried move towards and i tween but it is not working for.I want the character to move towards straight direction towards a object for few seconds and when he picks the balls he should return back to the old position where he started(no need of movement to return back to the old position re position is enough for the old position) and again he should move towards the object and this sequence should continue for ten times.return to old position no need of movement only reposition is enough .there should be delay between reposition to old position but movement is needed for move towards the object.I am using this script not in player it is kept in another empty game object.
Answer by aldonaletto · Aug 03, 2011 at 02:55 AM
If you just want to move some object in a straight line from point A to point B in some defined time, this function can do the job:
private var moving: boolean = false; // moving must be declared outside any function
function MoveObjFromTo(obj: Transform, pointA: Vector3, pointB: Vector3, time: float){ if (moving) return; // ignore other calls while moving moving = true; // signals "I'm moving already" var t: float = 0; while (t < 1){ t += Time.deltaTime / time; // sweeps from 0 to 1 in time seconds obj.position = Vector3.Lerp(pointA, pointB, t); // set position proportional to t yield; // leave the routine and return here in the next frame } moving = false; // finished moving } You can call this function to move your character from A to B in 10 seconds, then when you want it to go back, call it from B to A:
MoveObjFromTo(character, posA, posB, 10); while (moving) yield; // does nothing until the object reaches posB // the character does whatever it has to do and returns: MoveObjFromTo(character, posB, posA, 10); while (moving) yield; // does nothing until posA is reachedThis code can't be placed in Update or FixedUpdate functions ( yield isn't accepted in such functions), but you can place it in another function and call it from everywhere (including Update and FixedUpdate).
Your answer
![](https://koobas.hobune.stream/wayback/20220612165103im_/https://answers.unity.com/themes/thub/images/avi.jpg)