Standing Up While Crouching

Every time that I crouch and stand up under an object I phase through it, does anyone have a solution?
I don’t use rigid body so here’s the code

public class PlayerMotor : MonoBehaviour
{

    private CharacterController controller;
    private Vector3 playerVelocity;
    public float speed = 2f;
    private bool isGrounded;
    public float gravity = -9.8f;
    bool lerpCrouch = false;
    bool crouching = false;
    bool sprinting = false;
    float crouchTimer;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        isGrounded = controller.isGrounded;
        if (lerpCrouch)
        {
            crouchTimer += Time.deltaTime;
            float p = crouchTimer / 1;
            p *= p;
            if (crouching)
                controller.height = Mathf.Lerp(controller.height, 1, p);
            else
                controller.height = Mathf.Lerp(controller.height, 2, p);

            if (p > 1)
            {
                lerpCrouch = false;
                crouchTimer = 0f;
            }
        }
    }
    public void Crouch()
    {
        crouching = !crouching;
        crouchTimer = 0;
        lerpCrouch = true;
        if (crouching && sprinting)
            speed = 1;
        if (crouching)
            speed = 1;
        else
            speed = 2;
    }
    public void Sprint()
    {
        sprinting = !sprinting;
        if (sprinting)
            speed = 4;
        else
            speed = 2;
        if (crouching && sprinting)
            speed = 1;
    }
    public void ProcessMove(Vector2 input)
    {
        Vector3 moveDirection = Vector3.zero;
        moveDirection.x = input.x;
        moveDirection.z = input.y;
        controller.Move(transform.TransformDirection(moveDirection) * speed * Time.deltaTime);
        playerVelocity.y += gravity * Time.deltaTime;
        if (isGrounded && playerVelocity.y < 0)
            playerVelocity.y = -2f;
        controller.Move(playerVelocity * Time.deltaTime);
        Debug.Log(playerVelocity.y);
    }
}

Hey @brygonnn,

There are a few different ways to do this - considering you’re not using a RigidBody the simplest (imo) is to use a Raycast above the player.

Some code;

// Option A
if(Input.GetKeyDown(KeyCode.Space))
    if (!Physics.Raycast(transform.position, Vector3.up, 3f))
        Jump() / Stand();

// Option B
if (Input.GetKeyDown(KeyCode.Space))
{
    bool _isOverHead = Physics.Raycast(transform.position, Vector3.up, 3f);
    if (!_isOverHead)
        Jump() / Stand();
}

Gave two different implementations of the same thing, choose the one that fits your coding stye.

TL:DR :smiley:
You’d just need to apply this check for when you make the player standup. i.e un crouch.
if (!Physics.Raycast(transform.position, Vector3.up, 3f))

Hope that helps!