0

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);
BadmintonCat
  • 9,416
  • 14
  • 78
  • 129

2 Answers2

1

If I get you right, what you want is a constant velocity, which makes your objects arrive faster when the distance is shorter.

float speed = 2f; // 2 units per second

void Update()
{
    Vector3 distance = targetPosition - transform.position;
    float distanceLen = distance.magnitude;

    float stepSize = Time.deltaTime * speed;

    if (stepSize > distanceLen)
        transform.position = targetPosition;
    else
    {
        Vector3 direction = distance.normalized;
        transform.position += direction * stepSize;
    }
}
Thomas Hilbert
  • 3,559
  • 2
  • 13
  • 33
  • This works Ok but uses Update for tweening. In my case I want to use a dedicated Tweener to use easing equations and other features. – BadmintonCat Jan 04 '16 at 04:09
1

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);