- Home /
Problem with Vector3.Lerp
Hello Right now I am trying to use Vector3.Lerp to slide in a panel as part of my menu. However currently it returns a weird value overtime I try to do it. Here is my code using UnityEngine;
using System.Collections; using UnityEngine.UI;
public class MenuAnimations : MonoBehaviour {
public int WhichPanel;
public GameObject Panels;
public Transform Panel1Vector;
public Transform Panel2Vector;
public Transform Panel3Vector;
public Transform Panel4Vector;
public float speed;
public void MovePanel (int WhichPanel)
{
switch (WhichPanel)
{
case 0:
Panels.transform.position = Vector3.Lerp(Panels.transform.position, Panel1Vector.position, speed);
Debug.Log(Panel1Vector.position);
Debug.Log(Panels.transform.position);
break;
case 1:
Panels.transform.position = Vector3.Lerp(Panels.transform.position, Panel2Vector.position, speed);
Debug.Log(Panel2Vector.position);
Debug.Log(Panels.transform.position);
break;
case 2:
Panels.transform.position = Vector3.Lerp(Panels.transform.position, Panel3Vector.position, speed);
Debug.Log(Panel3Vector.position);
Debug.Log(Panels.transform.position);
break;
case 3:
Panels.transform.position = Vector3.Lerp(Panels.transform.position, Panel4Vector.position, speed);
Debug.Log(Panel4Vector.position);
Debug.Log(Panels.transform.position);
break;
}
}
}
For example, the Panel1Vector should be (125, 0, -8) but for some reason if I press my button to make WhichPanel = 0, the GameObject Panels goes to (369.1433, 0, -289.4084).
Does anyone know how to fix this or what my problem is.
Thank you
Dok
Answer by LazyElephant · Dec 24, 2015 at 11:03 AM
Unless you're varying the value of speed somewhere else, you're not using Vector3.Lerp correctly. Lerp works by returning the interpolation of the line between the two given vectors based on the third parameter, which should be between 0 and 1.
When you pass 0 to the Lerp function, it returns the first Vector3 argument. When you pass 1, it returns the 2nd Vector argument. If you pass 0.5, it returns a Vector3 half way between the two. So, in order to get a smooth transition between two Vector3s, you have to vary the 3rd argument over time. For example:
Vector3 pos = Vector3.Lerp( vector1, vector2, (Time.deltaTime / HowManySecondsYouWantItToTake) );
http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
As an alternative to Lerp, you could use Vector3.MoveTowards, which works in the way you are trying to use Lerp.
http://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html
You could also do all of this using animations. If you have time, I recommend this playlist by 3dBuzz on youtube. It covers a lot of information on UI development in a clearly explained way.
https://www.youtube.com/playlist?list=PLt_Y3Hw1v3QTEbh8fQV1DUOUIh9nF0k6c
Thank you for your answer I was able to fix the problem by making the Panel have the same parent as the Transforms Thank you