Create a Crouching System

Опубликовано: 10 Октябрь 2024
на канале: DitzelGames
9,789
164

I will show you how to create a Crouching System in Unity. You can use this for sitting or stealth action in your game. The hardest part is to prevent a the player to stand up, when he is under an object. We will prevent this by a raycast up. Have fun!

Code:

protected bool isCrouching = false;
protected CapsuleCollider CapCollider;

private void Crouch()
{
var crouchbutton = CrouchButton.Pressed || Input.GetKey(KeyCode.C);

if (!isCrouching && crouchbutton)
{
//crouch
CapCollider.height = 0.5f;
CapCollider.center = new Vector3(CapCollider.center.x, 0.25f, CapCollider.center.z);
isCrouching = true;
Actions.Sitting(true);
}

Debug.DrawRay(transform.position, Vector3.up * 2f, Color.green);
if (isCrouching && !crouchbutton)
{
//try to stand up
var cantStandUp = Physics.Raycast(transform.position, Vector3.up, 2f);

if (!cantStandUp)
{
CapCollider.height = 1f;
CapCollider.center = new Vector3(CapCollider.center.x, 0.5f, CapCollider.center.z);
isCrouching = false;
Actions.Sitting(false);
}
}
}