How can I lerp the player's scale when it becomes bigger or smaller?

Hello everyone,

I’ve made a little project that increases the player’s scale by one on each axis when the player presses space. I’m trying to figure out how to smoothly lerp between the old size of the player and the new size of the player. Currently, the change happens instantly and the player just snaps to its new size each time space is pressed. This was my initial code (attached to the player object):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScaleLerper : MonoBehaviour
{
    Vector3 originalSize = Vector3.one;
    Vector3 currentSize;
    public float multiplier;

    public float smoothTime;

    void Start() {
        if (currentSize == Vector3.zero) {
            currentSize = originalSize;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("space")) {
            currentSize += new Vector3(multiplier, multiplier, multiplier); 
            transform.localScale = currentSize;
        }
    }
}

and then I tried to use Vector3.Lerp, but it didn’t quite work.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScaleLerper : MonoBehaviour
{
    Vector3 originalSize = Vector3.one;
    Vector3 currentSize;
    public float multiplier;

    public float smoothTime;

    void Start() {
        if (currentSize == Vector3.zero) {
            currentSize = originalSize;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("space")) {
            currentSize += new Vector3(multiplier, multiplier, multiplier); 
            transform.localScale = Vector3.Lerp(transform.localScale, currentSize, smoothTime * Time.deltaTime);
        }
    }
}

Instead of smoothly transitioning between the localScale values, the player’s size still changed rigidly. Does anyone have any ideas?

This isn’t a situation where you’d use Lerp.

You’re better of using Vector3.MoveTowards. With it you can just continually adjust the scale towards the desired value.

1 Like

That’s because you’re only calling Lerp once.

If you want the scale to change over time you have to call it each frame with a continually increasing number for the third parameter for as long as you want it to last. The third parameter should be a number between 0 and 1: 0 is all-the-way-first-parameter and 1 is all-the-way-second-parameter. 0.5 is halfway between.

If you want to do something like this in a single function call, then you could use an animation clip, or you could search on the asset store for one of the many free “tween” libraries.

1 Like

Thank you both! I’ll try Vector3.MoveTowards() and what kdgalla said.

Yep, this worked perfectly. Thank you so much!

You can also try so called easing methods in conjunct with Lerp. Look it up.