- Home /
Mathf.lerp not finishing the lerp(age)
I am currently trying to make a Slider that smoothly goes from 0f to 100f, taking 100 seconds.
On my current way of making it work, that looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class swordui : MonoBehaviour
{
public Slider swordslider;
public float valuee;
public float speed = 0.01f;
public bool commit;
public void Awake()
{
commit = false;
valuee = 100f;
}
public void settozero()
{
valuee = 0f;
}
public void commitmoment()
{
commit = true;
}
public void Update()
{
swordslider.value = valuee;
if(commit == true)
{
valuee = Mathf.Lerp(swordslider.value, 100f, speed);
if (swordslider.value == 100f)
{
commit = false;
}
}
}
}
but this causes it to slow down by the end of the countdown. When I try to change it to:
valuee = Mathf.Lerp(0f, 100f, speed * Time.deltaTime);
it only counts up to 1, and then stops lerping.
How can I make it fully count from 0f to 100f, taking 100 seconds to do that, and without stalling by the end?
Answer by tyruji · Jul 05, 2021 at 11:07 PM
In the first case, you experienced one of the Zeno's paradoxes. Basically you are overwriting the initial value of the interpolation over and over, which in turn makes the interpolation non-linear. Your second approach is better, but you are not accelerating the time, your value will stay the same forever. What you should do is:
private float _timeAccel = 0;
private float _start = 0.0f, _end = 100.0f;
private float _speed = 0.01f;
private void Update()
{
value = Mathf.Lerp( _start, _end, _timeAccel );
_timeAccel += Time.deltaTime * _speed;
}
Also, don't worry if _timeAccel exceeds 1, the Lerp will always clamp it between 0 and 1. Good luck!
Your answer
Follow this Question
Related Questions
What's faster: Lerp or LerpUnclamped? (Performance) 1 Answer
how to use time on lerp 2 Answers
Mathf.Lerp happens instantly 2 Answers
Problem with Mathf.Lerp 1 Answer