How to negate my player getting stuck if there is something above his head while crouching ( unity 3d )?

Viewed 123

ive made this simple code to regulate the height of the player once Lcontrol is pressed

//crouching
if (Input.GetKey(KeyCode.LeftControl))
    controller.height = 1.0f;
else
    controller.height = 2.0f;

but my charachter gets stuck if there is a roof over his head while crouchin

  1. how do i make a function that detects if there is something above my head so even if i unpress the Lcontroll button my caracter stays crouched
  2. how do i lower the camera/body automatically because the camera rn gets stuck in the roof ( with the stuck player )

and you know generally be a smooth crouch ^^" , thanks in advance !

2 Answers

You can make one transform public "checkRoof ", put on the head of character and make something like this

 if (Input.GetButtonDown("Down") && (grounded || checkRoof == true))
    {
        anim.SetBool("pressDown", true);
        ChangeCollidersCrouch(); //change colliders (goes from character to character)
        crouched = true;
    }

    if (!Input.GetButton("Down") && grounded && checkRoof == false)
    {
        anim.SetBool("pressDown", false);
        anim.SetBool("Iscrouchwalk", false);
        ChangeCollidersIdle();
        speed = speedFix;
        crouched = false;
    }

To lower my camera I just attach it to my player so when my player gets smaller the camera goes down with it.

Related