Search code examples
c#unity-game-enginetransformscale

Crouch Script/ Scaling transform from one side only


Im trying to make a crouching script but there's something wrong with my code, I've been stuck in here for so many hours and I still don't know what's wrong.

Im basically just trying to decrease the height of my player transform to crouch, and increase it to stand up.

Here's my code:

public float crouchSpeed;
public float crouchWalkSpeed;
public bool isCrouching = false;
public bool isCrouched = false;

void Update () {

    Crouch();
    IsCrouchingVoid();
}

public void Crouch()
    {
        if(Input.GetKeyDown(KeyCode.LeftControl) && isOnGroud)
        {
            isCrouched = !isCrouched;
            isCrouching = true;
        }
    }

    public void IsCrouchingVoid()
    {
        if(!isCrouched)
        {
            if (isCrouching)
            {
                    Vector3 temp = transform.localScale;
                    temp.y -= crouchSpeed / 60;
                    temp.x = 1f;
                    temp.z = 1f;
                    transform.localScale = temp;

                if (temp.y <= 0.5f)
                {
                    temp.y = 0.5f;
                    isCrouching = false;
                }
            }
        }

        else if(isCrouched)
        {
            if (isCrouching)
            {
                    Vector3 temp = transform.localScale;
                    temp.y += crouchSpeed / 60;
                    temp.x = 1f;
                    temp.z = 1f;
                    transform.localScale = temp;

                if (temp.y >= 1f)
                {
                    temp.y = 1f;
                    isCrouching = false;
                }
            }
        }
    }

Thank you.

Edit:

Im using a CharacterController component so using the Physics.CapsuleCast feature isn't an option.


Solution

  • have you tried using CharacterController's height property?

    you can reduce its height in IsCrouchingVoid() method instead of just playing with scale to get behaviour of crouching.