I’m having a little trouble getting the Unity Lerp function to work the way I want it to, so I was hoping someone here could help me.
If I want one object to interpolate x-percent to the transform (position and rotation on all three axes) of another object, how would the code look for that?
One thing to keep in mind when lerping in an update loop:
If you lerp the position between the transform itself and another one, you are changing the position of the object itself. So next frame, the position you feed into the lerp will not be the same anymore. Thus you are not going to move at constant speed towards the target. If you want that you have to store the original transform in a variable and lerp between that and the new one. (See the second script)
So most commonly there are two cases of using a lerp with a transform over time:
Damping towards the target:
var target : Transform;
var damping = 3.0;
function Update ()
{
transform.position = Vector3.Lerp(transform.position, target.position, Time.deltaTime * damping);
transform.rotation = Quaternion.Slerp(transform.rotation, target.rotation, Time.deltaTime * damping);
}
And with constant speed towards the target over a specified time:
var target : Transform;
if (target)
StartCoroutine("Lerp", 1.0);
function Lerp (time : float)
{
var pos = transform.position;
var rot = transform.rotation;
var originalTime = time;
while (time > 0.0)
{
time -= Time.deltaTime;
transform.position = Vector3.Lerp(target.position, pos, time / originalTime);
transform.rotation = Quaternion.Slerp(target.rotation, rot, time / originalTime);
yield;
}
}
In both cases you have to assign the scripts to the object you start off with and assign the transform you want to end up with to target.