TommyE
TommyE

Reputation: 368

Unity - Change Local Scale based on Distance from Origin

I've been looking for a way of which I can adjust the size of a 2D game object, depending on the distance it is to the origin. When the game object has a distance of 4 units, it should have a local scale of (1,1,1). When it reaches the origin, it should have a local scale of (0,0,1). This should give the illusion that the game object is getting further away. If anybody knows how to achieve this it would be much appreciated for you to let me know.

Thanks in Advance,

Tommy

Upvotes: 1

Views: 4949

Answers (1)

user3797758
user3797758

Reputation: 1073

You could use linear interpolation on the scale value. Take the [Vector3][1] from the transforms local scale and pass in the distance from the origin.

To show some pseudo code of what I'm talking about:

get the transform
in the update figure out the distance from the origin
get the lerped value (Vector3.lerp(new Vector3(1,1,1), new Vector3(0,0,1), distance from center))

Added example code

public class Scaling : MonoBehaviour
{
    private Transform trans;

    void Start ()
    {
        trans = gameObject.transform;
    }

    void Update ()
    {
        float dist = Vector3.Distance(Vector3.zero, transform.position);

        //don't scale if further away than 4 units
        if(dist > 4)
        {
            transform.localScale = Vector3.forward;
            return;
        }

        //work out the new scale
        Vector3 newScale = Vector3.Lerp(Vector3.one, Vector3.forward, dist / 4);
        transform.localScale = newScale;
    }
}

enter image description here

Upvotes: 2

Related Questions