How can I invert lerp or just make smooth moves?

I want to be able to move an object to the position of the player in a smooth fashion. Lerp would be good in this form:

var start : Transform; var end : Transform; function Update () { transform.position = Vector3.Lerp(start.position, end.position, Time.time);

but the object always arrives at its destination in the same amount of time no matter the distance. I need the object to be moving on average at a constant velocity.

This form would be better:

var target : Transform; var smooth = 5.0; function Update () { transform.position = Vector3.Lerp ( transform.position, target.position, Time.deltaTime * smooth);

..giving it a realistic speed up slow down touch. However in this form it slows down the closer it gets to its target. I would like it to be slower at it leaves its position and speed up a bit to a constant velocity on its approach to its target

basically I would like to know how to make my object speed up to constant velocity and then slow down. How can do i do that? how to I make an object speed up?

Thanks a ton!

1 Answer

1

Use a coroutine like this:

var start : Transform;
var end : Transform;
var speed = 2.5;

function Start () {
	yield LerpPosition (start.position, end.position, speed);
}

function LerpPosition (start : Vector3, end : Vector3, speed : float) {
	var t = 0.0;
	var rate = 1.0/Vector3.Distance(start, end) * speed;
	while (t < 1.0) {
		t += Time.deltaTime * rate;
		transform.position = Vector3.Lerp(start, end, Mathf.SmoothStep(0.0, 1.0, t));
		yield;
	}
}

i know i'm slowpoke, but can you explain how to use it?

Put that script on an object, then drag in objects from the hierarchy that represent the start and end positions for the lerp.

@Eric5h5 +1 and 4K :) I checked your website..!! Pretty cool things!

Is there a way to accomplish this without using yield? I have a script with a 'destination' as Vector3 (sometimes updated from another script) and a max-speed variable as float, this technique proved difficult to implement onto that. Would it be ideal to add it as a separate component?

You can't have a coroutine without using yield. You can use [MoveObject][1] for more flexibility. [1]: http://wiki.unity3d.com/index.php?title=MoveObject