- Home /
Vector3.Lerp isn't working
Hello,
An enemy is appearing in a random position every to seconds, and it's supposed to hame a smooth movement, to add +1 to it's y axis. Like a mole that goes out of its hole!
But it doesn't work! The enemy bumps like a shaker for ever! What's wrong?
#pragma strict
private var curPos : Vector3;
private var newPos : Vector3;
function Start () {
curPos = transform.position;
newPos = new Vector3(transform.position.x, transform.position.y + 2, transform.position.z);
}
function Update () {
transform.position = Vector3.Lerp(curPos, newPos, Time.deltaTime);
}
Answer by robertbu · Oct 05, 2013 at 07:44 PM
When using 'Time.deltaTime' in a Lerp(), you need to update the current position each frame, not in Start:
#pragma strict
var speed = 0.75;
private var newPos : Vector3;
function Start () {
newPos = new Vector3(transform.position.x, transform.position.y + 2, transform.position.z);
}
function Update () {
transform.position = Vector3.Lerp(transform.position, newPos, Time.deltaTime * speed);
}
I've added 'speed' so you can control the speed of the movement. This will create an eased movement towards the end. If you don't want an eased movement, replace the Vector3.Lerp() with Vector3.MoveTowards() and adjust 'speed'.
Many of the other solutions will work, but I wanted to correct the perception that you had to put in values ranging from 0 to 1 to get Lerp() to work. Using deltaTime like this is a non-traditional use of Lerp(), but it is very common in Unity.
Answer by DarkPixel · Oct 05, 2013 at 07:24 PM
As the doc says, it used to interpolate between 2 vector, the last parameter (t) need to be between 0 and 1.
You probably need to use a member in your class to store the current T value. And in the update:
void Update()
{
if (T > 1.0f)
return;
T = T + ((speedPerSecond * Time.deltaTime) / distanceBetweenThe2Pos);
transform.position = Vector3.Lerp(curPos, newPos, T);
}
Answer by meat5000 · Oct 05, 2013 at 07:36 PM
At 30 FPS one frame is 0.033 Seconds. Your Lerp will have your transform.position move once to a position very very close to curPos. This is because deltaTime is roughly the same every frame and t = 0.03 represents 3% of your movement. Lerp works with t between 0 and 1. 0 represents curPos, 1 represents newPos and values between 0 and 1 will scale your Lerp between curPos and newPos, so t = 0.5 is halfway between the two.
Make your own timer
timer = 0;
timer += Time.deltaTime;
Use it to Lerp then reset it.
If lerpTime = 5; // Desired time to complete lerp
timer/lerpTime = 1 when timer = 5. //At t=1 Lerp is complete.