How to implement CROUCH in a self-made Player movement script.

My player keeps falling through the floor.

public class Player_Movement : MonoBehaviour {

	private float current_speed = 10f;
	public static float walk_speed = 10f;
	private float crouch_speed = 0.5f * walk_speed;
	private float run_speed = 1.6f * walk_speed;
	private float jump_speed = 1.2f * walk_speed;
	float vert_vel = 0;
	float height;
	Transform tr;
	CharacterController control;

	private Vector3 dir = Vector3.zero;

	// Use this for initialization
	void Start () {
		Screen.lockCursor = true;
		tr = transform;
		control = GetComponent<CharacterController>();
		height = control.height;
	}
	
	// Update is called once per frame
	void Update () {

		float h = height;
		
		vert_vel += Physics.gravity.y * Time.deltaTime;
		dir = transform.rotation * new Vector3( Input.GetAxis("Horizontal") , 0, Input.GetAxis("Vertical") );

		if (dir.magnitude > 1f) {
			dir = dir.normalized;
		}

		if (control.isGrounded && Input.GetButton("Sprint")) {
			current_speed = run_speed;
		} else if (control.isGrounded && Input.GetButton("Crouch")) {
			current_speed = crouch_speed;
			h = height*0.5f;
		} else if (control.isGrounded && Input.GetButton("Jump")) {
			vert_vel = jump_speed;
		} else {
			current_speed = walk_speed;
		}

		float ultScale = tr.localScale.y; // crouch/stand up smoothly
		
		Vector3 tmpScale = tr.localScale;
		Vector3 tmpPosition = tr.position;
		
		tmpScale.y = Mathf.Lerp(tr.localScale.y, h, 5 * Time.deltaTime);
		tr.localScale = tmpScale;
		
		tmpPosition.y += (control.height / 2) * (tr.localScale.y - ultScale); // fix vertical position
		tr.position = tmpPosition;
		Vector3 movement = dir * current_speed * Time.deltaTime;
		
		movement.y = vert_vel * Time.deltaTime;

		control.Move(movement);

		aim_camera();
	}

	void aim_camera()
	{
		Camera myCamera = this.GetComponentInChildren<Camera>();
		
		if (myCamera == null) {
			Debug.LogError("No camera");
			return;
		}
		
		float AimAngle = 0;
		
		if(myCamera.transform.rotation.eulerAngles.x <= 90f) {
			AimAngle = -myCamera.transform.rotation.eulerAngles.x;
		}
		else {
			AimAngle = 360 - myCamera.transform.rotation.eulerAngles.x;
		}
	}
}

Here’s a link that has the solution. It worked for me :slight_smile:

How to Make the FPS Character Controller RUN and CROUCH