Using lerp properly
I feel like this should be simple, but I just cant get the desired outcome. I am trying to move an object with a lerp over .5 seconds when a button is pressed, this is my script:
public GameObject player;
public GameObject reference;
float lerpTime = .5f;
float currentLerpTime;
Vector3 startPos;
Vector3 endPos;
bool click;
public void OnClick ()
{
click = true;
}
void Start ()
{
startPos = player.transform.position;
endPos = reference.transform.position;
}
void Update ()
{
if (click == true) {
currentLerpTime = 0f;
}
currentLerpTime += Time.deltaTime;
if (currentLerpTime > lerpTime) {
currentLerpTime = lerpTime;
}
float perc = currentLerpTime / lerpTime;
player.transform.position = Vector3.Lerp (startPos, endPos , perc);
}
}
All that happens is that when I play, my object slides forwards and then the buttons do nothing. I have also tried not using startPos and endPos and just using player.transform.position ect... in the lerp function. That works but the object teleports, and has no smooth movement.
Answer by We_we_we · May 20, 2016 at 11:24 PM
Sorry for the late reply.
I tried what you showed me, but it just wouldn't work.
Instead of using a lerp for what I wanted to do, I just set up my own increments to do in update by dividing the offset of player and reference by ten. I then checked if the increments equal the offset, if they do, click equals false.
I hope this helps anyone who has the same problem I did.
Answer by NoseKills · May 20, 2016 at 05:59 AM
You must only reset the timer once when the button is clicked, not every time in Update after it is pressed. If nothing is clicked, you shouldn't do anything in Update.
public void OnClick ()
{
click = true;
currentLerpTime = 0f;
}
void Start ()
{
startPos = player.transform.position;
endPos = reference.transform.position;
}
void Update ()
{
if (!click) {
return;
}
currentLerpTime += Time.deltaTime;
if (currentLerpTime > lerpTime) {
currentLerpTime = lerpTime;
}
float perc = currentLerpTime / lerpTime;
player.transform.position = Vector3.Lerp (startPos, endPos , perc);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612081152im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Object moving problem 0 Answers
Smooth camera to target Y-height 3 Answers
Objects not moving smoothly with Vector3.Lerp 2 Answers
Player movement 0 Answers