# Crouching Script

Can anyone explain to me the code in the update function as I am having a hard time making sense of it.

``````#pragma strict

var walkSpeed : float = 7;
var crouchSpeed : float = 3;

private var charMotor : CharacterMotor;
private var charController: CharacterController;
private var theTransform : Transform;
private var charHeight: float;

function Start ()
{
charMotor = GetComponent(CharacterMotor);
theTransform = transform;
charController = GetComponent(CharacterController);
charHeight = charController.height;
}

function Update ()
{
var h = charHeight;
var speed = walkSpeed;

if (Input.GetKey("c"))
{
h = charHeight *0.5;
speed = crouchSpeed;
}

charMotor.movement.maxForwardSpeed = speed;

var lastHeight = charController.height;
charController.height = Mathf.Lerp(charController.height, h, 5*Time.deltaTime);
theTransform.position.y += (charController.height - lastHeight)/2;
}
``````

line 33 lerps the character controller height from its current height to h (h is either standing height or crouched height).

line 34 repositions the character so it doesn’t fall through the floor when scaling to a larger height, and doesn’t appear floating when scaling to a smaller height.

Edit :

Try and imagine it with real values.

From Standing to Crouching :

line 32 : lastHeight is 1

line 33 : imagine this set charController.height to 0.5

line 34 : (charController.height - lastHeight)/2 = (0.5 - 1) / 2 = -0.25

theTransform.position.y += -0.25 , so it lowers the position Y so that the bottom of the collider is still on the ground

From Crouching to Standing :

line 32 : lastHeight is 0.5

line 33 : imagine this set charController.height to 1

line 34 : (charController.height - lastHeight)/2 = (1 - 0.5) / 2 = 0.25

theTransform.position.y += 0.25 , so it raises the position Y so that the bottom of the collider is still on the ground