How to check if there is a ceiling above the player?

Viewed 117

I added crouching to my movement script, what messing is to check if there is a ceiling above the player, and if there is the player should remain crouched. How would I achieve this?

currently, for crouching, the user should press the c key and if he wants to stand up, he should press it again.

enter image description here

UPDATED CODE:

if (crouching)
        {
            isRunning = false;
            transform.localScale = new Vector3(transform.localScale.x, crouchYScale, transform.localScale.z);
            movement = (move.y * transform.forward) + (move.x * transform.right);
            controller.Move(movement * crouchSpeed * Time.deltaTime);
        }
        else
        {
            
            transform.localScale = new Vector3(transform.localScale.x, startYScale, transform.localScale.z);
            movement = (move.y * transform.forward) + (move.x * transform.right);
            controller.Move(movement * moveSpeed * Time.deltaTime);
        }

 controls.Player.Crouch.performed += _ => OnCrouch(); 

Here is my attempt:

public void OnCrouch()
    {

        RaycastHit hit;

       bool checkCeiling =  Physics.Raycast(transform.position, -Vector3.up, out hit, 2f);
        if (crouching && checkCeiling == true)
        {
            crouching = false;
        }
        else
        {
            crouching = true;
        }
    }

But this does not show any result. the Player still can stand up even if there is a near ceiling above his head. How can I prevent standing up if there is a near ceiling and allow it only when there is enough space to stand up? please help.

1 Answers

Most game logic allows to uncrouch only if there is no ceiling above the player, but does not auto-crouch upon approaching low-ceiling areas. In your toggle function, do the ray cast like this:

public void OnCrawl()
{
  if(crouching && Physics2D.Raycast(transform.position, Vector2.up, 2f).collider == null) 
    crouching = false;
  else 
    crouching = true;
}

Keep the rest of your code as is and you should be good to go.

Related