[SOLVED] localScale a gameobject on a keypress using acceleration/deceleration?

Hi,

This might be a stupid question, but is it possible to use transform.localScale along with acceleration?
I can increase/decrease the height of my gameobject on certain keypresses, but I want the scaling to speed up gradually until it reaches a certain speed, and when I release the key I want the scaling to decelerate before it stops completely. Right now my gameobject scales instantly, which is not very realistic.

This is the code I have so far:

void Update() {
        if (Input.GetKey(KeyCode.UpArrow)) {
            transform.localScale += new Vector3(0, 0.1f, 0);
        }
        else if (Input.GetKey(KeyCode.DownArrow)) {
            transform.localScale += new Vector3(0, -0.1f, 0);
        }
    }

Sure it’s possible. It’s just a bit of math.

You’ll want to add a “scaleVelocity” property to your class, initially zero. When a key is pressed, you increase or decrease this property (by some amount * Time.deltaTime), within limits. When no key is pressed, you change the value towards zero (again by some amount * Time.deltaTime). And whenever scaleVelocity is nonzero, you use that to update localScale.

1 Like

Thank you so much! I got it working now. This is the code I ended up with:

private float scaleSpeed = 0f;
    private float scaleAcceleration = 2f;
    private float maxScaleSpeed = 4f;

    void Update() {
        if (Input.GetKey(KeyCode.KeypadPlus) && (scaleSpeed < maxScaleSpeed)) {
            scaleSpeed = scaleSpeed + scaleAcceleration * Time.deltaTime;
        }
        else if (Input.GetKey(KeyCode.KeypadMinus) && (scaleSpeed > -maxScaleSpeed)) {
            scaleSpeed = scaleSpeed - scaleAcceleration * Time.deltaTime;
        }
        else {
            if (scaleSpeed > scaleAcceleration * Time.deltaTime) {
                scaleSpeed = scaleSpeed - scaleAcceleration * Time.deltaTime;
            }
            else if (scaleSpeed < -scaleAcceleration * Time.deltaTime) {
                scaleSpeed = scaleSpeed + scaleAcceleration * Time.deltaTime;
            }
            else {
                scaleSpeed = 0;
            }
        }
        if (scaleSpeed != 0) {
            transform.localScale += new Vector3(0, 0, scaleSpeed);
        }
    }
1 Like

Looks about right, except that line 13 should just say if (scaleSpeed > 0), and line 16 should just say else if (scaleSpeed < 0). And you won’t need the else clause on lines 19-21 at all.