Random Code: Player Crouching

Unity includes prefabs for 1st- and 3rd-person characters, but they lack some basic movement features such as sprinting and crouching, which I find to be a little bit stupid, so I’ve written code to do this for me. It’s simple really – it starts by finding the character controller component attached to the player, then gets his (or her, equality fans) height, then when the player is holding the ‘c’ key, it scales down the character controller height so your player can squeeze into tiny gaps –  just attach a script with this code in it to your player and it should work. So, just for you, here is my code for crouching!

private var controller: CharacterController;
private var charHeight: float;

function Start()
{
    charController = GetComponent(CharacterController);
    charHeight = controller.height;
}

function Update()
{
    var height = charHeight;

    if(Input.GetKey("c"))
    {
        height = charHeight / 2;
    }

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

How it works!

Firstly, the variable controller stores the character controller, then charHeight stores a float. In the start function, it finds the controller attached to the player and defines charHeight as the controller’s height as a reference point. Then in the update function, it takes the height at the start of each frame, then if the ‘c’ key is held down, it basically halves the height (smoothing it by using Mathf.Lerp, which takes the first parameter given to it and changes it to the second parameter over time, changing by the third parameter each frame, so basically in this case it takes the normal character height and changes it to half that by 5 units each second, through use of Time.deltaTime to ensure the change is framerate-independent. If that all made sense.) and moves the whole transform down in the y-direction by half the change in height, to match the change in the controller’s height. The net change is that, when the “c” key is held down, the player, along with the colliders and camera attached to him/her, crouches down. Feel free to use this code in your own projects, and if you have any improvements, you can post a comment here. Have fun crouching, and if none of my explanation made sense, just post a comment and I’ll get back to you 🙂

Advertisements