Hey there!
I have tried to write code for crouching for a long time and write or find one that works as well as I want it to. I gave up and decided to use animations (“Crouch Up” and “Crouch Down”). I wrote some code that works almost perfectly but the problem is that it’s too long; I was wondering if someone could help me make it shorter (I like things to be as close to perfect as possible, since perfect is not possible).
Additional problem: [When I’m moving while crouching, if I crouch up a little before I reach for example a table, since the crouching up takes a little time, the player will crouch up into the top of the table. I fixed it (you can see it in the code) but since it’s an animation it’s kinda buggy; The player starts the “crouch up” animation while canCrouchUp is true, canCrouchUp turns false because the player is currently under something, the “crouch up” animation continues playing, then instantly the “crouch down” animation starts playing because based on the code, the player should be crouching.]
public bool canCrouchUp;
void Crouching()
{
if (Input.GetButtonDown("Crouch") && canCrouchUp)
{
isCrouched = !isCrouched;
}
if (!isCrouched)
{
movementSpeed = walkingSpeed;
if (canCrouchUp)
{
GetComponent<Animator>().Play("Crouch Up");
}
else
{
isCrouched = true;
}
}
else
{
GetComponent<Animator>().Play("Crouch Down");
movementSpeed = crouchSpeed;
}
if (isCrouched && !canCrouchUp)
{
GameObject.Find("cantStandText").GetComponent<Text>().text = "Can not stand up here.";
}
else { GameObject.Find("cantStandText").GetComponent<Text>().text = null; }
}
In Update I have:
canCrouchUp = !Physics.CheckCapsule(transform.position + new Vector3(0f, -0.325f, 0f), transform.position + new Vector3(0f, 0.675f, 0f), 0.25f, crouchingLayer); //CheckCapsule to not crouch up into something.