How to check if there is a collider above and then uncrouch

Hello, first sorry if I ever make a mistake because I’m not an English … so, let me just introduce you the question. I have a simple but very nice Crouch sytem for my character, but when I stand/uncrouch and there is some kind of ceiling above the character (collider), the char goes through the colider and stucks there until I crouch and go somewhere else where there is not a collider above. I tried some ceiling checks, but they didn’t help in any way … so can, you someone of you guys help me, here is my code:

private bool isCrouching = false;
private Transform theTransform;
private float charHeight;

void Start()
{
    theTransform = transform;
    charHeight = CharCont.height;
}

public void Update()
{
        float h = charHeight;
		float speed = WalkSpeed;
		
		if(Input.GetKey (KeyCode.C))
		{
			h = charHeight*0.5f;
			isCrouching = true;
		}
		else
			isCrouching = false;
		
		float lastHeight = CharCont.height;
		CharCont.height = Mathf.Lerp (CharCont.height, h, 5*Time.deltaTime);
		theTransform.position = new Vector3	(theTransform.position.x, theTransform.position.y+(CharCont.height-lastHeight)/2, theTransform.position.z);
}

So is there a way to implement a checkForCeiling system, or anykind of system that prevents character to go through ceilings?

1 Answer

1

There are a lot of ways you could do this - I would probably start with doing a raycast upward to make sure there’s nothing above within an appropriate distance before allowing the character to stand back up.

can you give me an example, because I already tried with a raycast but it did continue go through the ceiling .. can you write a code that will work with the one I have, please !?