Hi everybody, first time asking a question here. My question is about the lerp function.
I have a character I want moved from it’s current position to another gameobjects position when i click on it, it all works with moving there but i want it animate there. What exactly should I be doing so it will animate there instead of just instantly going to the position?
In your case, using a coroutine and Lerp is probably the best solution:
var moving = false; function MoveTo(obj: Transform, dest: Vector3, duration: float){ if (moving) return; // abort call if already moving moving = true; // set flag to indicate "I'm moving" var orig: Vector3 = obj.position; // save the initial position var t: float = 0; // start position indicator (0=orig, 1=dest) while (t < 1){ t += Time.deltaTime / duration; // increment proportionally the indicator obj.position = Vector3.Lerp(orig, dest, t); // set new position yield; // let Unity free until next frame } moving = false; // clear flag to show the coroutine has ended }
The moving flag is important to avoid multiple calls to MoveTo: coroutines run independently in the background, thus calling MoveTo while the previous one has not finished will result in several MoveTo instances running at the same time, with weird or disastrous results.
Example: Move this object to the position of the empty object destObject in 2 seconds when key M is pressed:
if (Input.GetKeyDown("m")){
MoveTo(transform, destObject.transform.position, 2);
}
NOTE: Lerp doesn’t check for collisions. If you want to take collisions into account, the object must be a Rigidbody (will react wildly to collisions) or a CharacterController (needs a completely different MoveTo function)