Crouching teleports character underground

When I press left shift (crouching) my character falls through the ground, what ofc shouldn’t happen. I compared my script to other scripts on the internet but the code seems fine, so idk why it’s happening :confused:

Here’s the code: (I won’t paste everything because that would be too much)

private void MyInput()
	{
		horizontalInput = Input.GetAxisRaw("Horizontal");
		verticalInput = Input.GetAxisRaw("Vertical");

		if(Input.GetKey(jumpKey) && readyToJump && grounded)
		{
			readyToJump = false;
			Jump();

			Invoke(nameof(ResetJump), jumpCooldown);
		}

		if (Input.GetKeyDown(crouchKey))
		{
			transform.localScale = new Vector3(1f, crouchYScale, 1f);
			rb.AddForce(Vector3.down * 1f, ForceMode.Impulse);
		}

		if (Input.GetKeyUp(crouchKey))
		{
			transform.localScale = new Vector3(1f, startYScale, 1f);
		} 
	}

And here an image of how I set up the player:

Thanks in advance!

Your problem is related to collision detection with plane in physics collision system. Also changing transforms scale not applies changes to physical collider immediately, as I remember. There are two options to solve your problem.

  1. First:
    Try changing force mode from ForceMode.Impulse to ForceMode.Force - this would make your capsule to move down faster after starting crouch, but won’t solve problem.

  2. Second:
    Change transform position directly from code, not by physics system. Like in code below:

    var position = transform.position;
    position.y -= 0.5f;
    transform.position = position;
    

I hope it would help you.
And some useful links: