Math calculation question

Hi, so I’m doing some sprite scaling and I need to smoothly increase an objects scale over the distance between its start point and end point so that the scale is back to 1 when it reaches the end point not before.

I basically need to adjust the speed that it scales based on the time it takes to get from point A to point B.

Can anyone help me out with the math for this because I don’t know where to start.

I think the term you are looking for is linear interpolation, AKA lerp.

1 Like

Like @BIGTIMEMASTER said based on the description you can just use Lerp. Wikipedia link has the actual math behind it but there’s no reason to implement the math yourself unless you need double precision math.

for extra info/reference,
theres many Tweening packages for unity, like this (to easily do that kind of effects)

1 Like

Speaking of which, this is related:
https://easings.net/

1 Like

If you want to easily visualize the different easing equations in Unity with a simple easing library there is this
Unity Easing Library Visualisation

See if this makes any sense: let’s suppose you know the total distance to go is DIST_ALL and can figure out how far away from the start you are now in DIST_FROM_START. For example, the two points as 16.4 away and you’ve currently gone 5.2 of that. It’s usually easier to convert that to a percent, as a 0-1. We’ll use d for that, computing it as: (DIST_FROM_START/DIST_ALL).

We want the size to increase as we go from d=0 to d=0.5, then go back down as d goes to 1 (it reaches the end). It’s also easier here to forget the real sizes and use a percent from 0 to 1, back down to 0. 0 means no increase, 1 means full increase to max size. There might be some clever math way of doing it, but an IF will work:

float s; // from 0 to 1. The percent size increase, 0=no increase / use start size
if(d<=0.5f) s=d*2; // check: d=0/s=0, d=0.5/s=1
else s=2-d*2; // check: d=0.5/s=2-1, d=1/s=2-2

Figuring out that 2-d*2 line seems tricky, but the secret is: we know size goes down as d goes up, so for sure there will be -d somewhere.

Finally we have to convert that 0-1 size increase into the scale, which goes from 1(normal size) to 7(for example). This looks ugly, but SCALE=1+6*s should work. Or if the largest size is S it’s the uglier: SCALE=1+(S-1)*s;.

1 Like

You can also use an AnimationCurve for this stuff, which allows you to tune things visually rather than by working out the match which gets the result you want.

From vague memory only:

[SerializeField] private AnimationCurve scaleCurve = null; // This will show in the Inspector

void Update()
{
    // Do stuff and calculate fraction along path
    float scale = scaleCurve.Evaluate(fractionAlongPath);
    // Apply the scale
}