Timiibo
Timiibo

Reputation: 1

Calculating the speed a sprite changes size based on the distance it needs to travel and speed it is travelling

I am doing some sprite scaling and have a sprite starting at scale 0.2 on the x+y axis it travels at a constant speed (10) between its start point and end point increasing in scale as it travels.

I need it to scale evenly across that distance so that when it reaches its end point it is at its final scale (0.2 - 1).

Now because the distance changes based on where it spawns the time that it takes to scale in size must also change so that it can scale evenly across the distance, what I need is the calculation to work out the 'scale speed' based on the distance it is traveling and speed the item is moving.

I'm getting the distance between the two points with Vector3.Distance

distance = Vector2.Distance(transform.position, centerScreen);

This scales the object over time

if (transform.localScale.x < 1 && transform.localScale.y < 1)
   {
    transform.localScale = new Vector3(transform.localScale.x + scaleSpeed * Time.deltaTime, transform.localScale.y + scaleSpeed * Time.deltaTime, 1);
   }

and the object moves at a speed of 10

My question is, How do I calculate the scale speed based on the distance and speed the object is traveling?

Upvotes: 0

Views: 190

Answers (1)

The Justice King
The Justice King

Reputation: 300

In Unity, there is a function called InverseLerp, which creates a point from 0 - 1 based on how far the value v is between the values a and b. It is the opposite of the Lerp function. (https://docs.unity3d.com/ScriptReference/Mathf.InverseLerp.html).

Here is example code for your situation: float sizeVal = Mathf.InverseLerp(0, yourSetDistance, distance) * 0.8f + 0.2f;

This changes the range of the inverse lerp to between 0.2 and 1. Use the sizeVal in the size vector. If this isn't what you wanted, please explain in more detail or restate your question.

Upvotes: 1

Related Questions