I have a Vector3.Lerp in an Update function but it doesn’t seem to move my object. This is my script:
private var elfMale;
public var smooth = 2;
private var newPosition;
function Awake ()
{
//newPosition = elfMale;
}
function Start ()
{
elfFemale = GameObject.Find ("FemaleElf").transform.position;
elfMale = GameObject.Find ("MaleElf").transform.position;
}
function Update ()
{
if (move)
{
newPosition = new Vector3 (10, 10, 0);
elfMale = Vector3.Lerp (elfMale, newPosition, Time.deltaTime * smooth);
}
}
I used the Unity Official Tutorials video and they put: newPosition = elfMale in the Awake function but I’ve commented it out since it seems pointless for me. Any ideas of why this isn’t working? Also, I’ve activated the move variable through a GUI button.
You’re misunderstanding the parameter to Lerp. I’ll quote an old forum post of mine to explain.
I usually just explain the lerp parameter as a percentage. Given a t from 0 to 1, you’ll get a result that is t percent between a and b.
If you want a value that changes over time, t needs to change over time.
This example is in C#, but the fundamental considerations are identical:
public float min = 0f;
public float max = 100f;
public float lerpTime = 1f;
float currentLerpTime = lerpTime + 1f;
public void StartLerping() {
currentLerpTime = 0f;
}
void Start() {
StartLerping();
}
void Update() {
currentLerpTime += Time.deltaTime;
if (currentLerpTime <= lerpTime) {
float perc = currentLerpTime / lerpTime;
float current = Mathf.Lerp(min, max, perc);
Debug.Log("current: " + current);
} else {
Debug.Log("finished");
}
}
In your case, you’re passing currentTime.deltaTime to Lerp. That’s only the time for the current frame. The above example instead uses a value which increases byTime.deltaTime once per frame, representing the total time that has passed since we started lerping.
public class CameraScript : MonoBehaviour
{
// Start is called before the first frame update
bool isGoing;
float starttime,fraction,time;
Vector3 a, b;
void Start()
{
isGoing = false;
fraction = 0;
}
// Update is called once per frame
void Update()
{
if (isGoing)
{
fraction = (Time.time - starttime) / time;
Debug.Log(fraction + " a: " + a + " b: " + b);
if (fraction > 1)
{
isGoing = false;
return;
}
transform.position = Vector3.Lerp(a, b, fraction);
}
}
public void LerpIt(Vector3 a, Vector3 b, float time)
{
Debug.Log("Entered");
starttime = Time.time;
this.a = transform.position;
this.b = b;
this.time = time;
isGoing = true;
//transform.position = b;
}
}
in my case, I was simply writing Vector3.Lerp();
the mistake was transform.position = vector3.lerp();