- Home /
Smooth translation
I'm trying to get a gameObject to move smoothly to a certain position (defined in a Vector3 variable), and I've been told to use Vector3.Lerp. But, when I do, the object doesn't move smoothly, it just moves to the target in one frame. Here is my code:
var start : Vector3;
var end : Vector3;
transform.position = Vector3.Lerp(start,end,Time.deltaTime);
Answer by Ipsquiggle · Apr 01, 2012 at 10:03 PM
The 3rd parameter of Lerp is a ratio from 0 to 1, where 0 means start, 1 means end.
So you'll want to do something like this:
var lerpPosition : float = 0.0f;
var lerpTime : float = 5.0f; // This is the number of seconds the Lerp will take
var start : Vector3;
var end : Vector3;
function Update() {
lerpPosition += Time.deltaTime/lerpTime;
transform.position = Vector3.Lerp(start,end,lerpPosition);
}
So what's happening here is that we start with a lerpPosition
of 0 (putting our instance at start
), and each frame we add a small amount to it. After a few seconds (5 in this example), lerpPosition
will have increased to 1.0, putting our instance at end
.
This way you can also easily tell that the Lerp is complete by testing if (lerpPosition >= 1.0f)
.
Hope that helps.
Answer by fnc12 · Jan 31, 2014 at 08:58 AM
Vector3.Lerp does not make a smooth movement. It calculates a new vector in fraction between two vectors. Imagine: you have start point with x=5 and finish point with x=10. So Lerp(5,10,0.5) returns 7.5 because the third parameter is 0.5 that is half of the way is passed; Lerp(5,10,1) returns 10 (the end of the way), Lerp(5,10,0) returns 0 and so on. In your case you have to store fraction (the third parameter), increment it every frame and assign a new transform to your object every frame until fraction equals or greater that 1. After that you get the smooth movement.
Vector3.Lerp does not make a smooth movement itself. It calculates a new vector in fraction between two vectors. For example: you have start point with x=5 and finish point with x=10. So Lerp(5,10,0.5) returns 7.5 because the third parameter is 0.5 that is half of the way is passed; Lerp(5,10,1) returns 10 (the end of the way), Lerp(5,10,0) returns 0 and so on. Lerp make the same thing in 3D. In your case you have to store fraction (the third parameter), increment it every frame and assign a new transform to your object every frame until fraction equals or greater that 1. After that you get the smooth movement.
Your answer
Follow this Question
Related Questions
Weapon Movement Freezing 0 Answers
Vector3.Lerp Only working once 1 Answer
Vector3 Lerp using Time.deltaTime? 3 Answers
Vector3 Lerp finish too quicly 1 Answer
How to smooth my camera (Vector3.Lerp) 0 Answers