How to change scale of an object from the bottom instead of center?

What I need it to do is change the scale on the y axis of the box from 3 to 2 on leftcontrol down, then back to 3 when leftcontrol comes up. It works fine, but instead of changing the scale from the center and taking 0.5 off of the top and bottom of the box like it is now, how can I make it take 1 off of the top of the box? Ignore the movementSpeed, that just makes the player slower when crouched.

      if(Input.GetKeyDown(KeyCode.LeftControl)){
            transform.localScale = transform.localScale + new Vector3(0, -1, 0);
            movementSpeed = 3;
        }
        if(Input.GetKeyUp(KeyCode.LeftControl)){
            transform.localScale = transform.localScale + new Vector3(0, 1, 0);
            movementSpeed = 10;
        }

You have to offset the box too, by the amount required to keep the lower edge the same.

The above code will instantly change between the two values. You might want a more gradual approach. Here’s one way:

Smoothing movement between discrete values:

The code: Smooth movement - Pastebin.com

I would keep one float value that is your “crouchedness,” say from 0 to 1.

Then I would derive scale and offset from that and directly set the localScale and localPosition.

I would NOT read the scale or position back: you explicitly create it based on the crouchedness going from 0 (standing) to 1 (crouching):

scale would be perhaps 2 - crouchedness

offset would be perhaps crouchedness / 2… I think that would work (only on the Y axis obviously).

That worked great! I just added “transform.position = transform.position + new Vector3(0, -0.5f, 0);” under the keydown, then just switched -0.5 to 0.5 for the keyup.

1 Like