Search code examples
mathunity-game-enginetweenlerp

Tween time based on distance


I'm tweening several game objects (with LeanTween) and want the time to be shorter if the distance between distance points a and b are shorter. I used to write my own forumla for it years ago but forgot it (duh). Can somebody give me a hint? And is Mathf.Lerp (or similar) of any use here? If I use the following, it does exactly the opposite (time gets longer the shorter the distance, which is what I don't want) ..

float time = Mathf.Lerp(source.transform.position.y, target.transform.position.y, Time.time);

Solution

  • From docs http://docs.unity3d.com/ScriptReference/Mathf.Lerp.html

    public static float Lerp(float a, float b, float t);

    Linearly interpolates between a and b by t. The parameter t is clamped to the range [0, 1].

    So, time variable in your sample will be equal to target.transform.position.y in most cases because Time.time is increasing. That's why your time became longer.

    Following code will give reduced time depended by traveled distance (tweenObject is a object controlled by LeanTween)

    float time = Mathf.Lerp(tweenObject.transform.position.y, 
    target.transform.position.y, 
    source.transform.position.y / tweenObject.transform.position.y);