I am using the standard first person character controller and wanted to enable crouching. I added the following script to it, based on one I found in another question on this site.
using UnityEngine;
using System.Collections;
public class CrouchController : MonoBehaviour
{
private CharacterController character;
private float initialHeight;
void Awake()
{
character = GetComponent<CharacterController>();
initialHeight = character.height;
}
void Update()
{
float newHeight = Input.GetButton("Crouch") ? 0.5f * initialHeight : initialHeight;
float currentHeight = character.height;
character.height = Mathf.Lerp(currentHeight, newHeight, 5 * Time.deltaTime);
transform.position = transform.position + new Vector3(0, (character.height - currentHeight) / 2, 0);
}
}
This works perfectly except for one small detail. If I crouch and move beneath a collider, then release crouch, I will return to full height and pass through the collider. I would like the player to simply stop when this kind of collision occurs, but I’m having a hard time figuring out how to do this. It doesn’t seem like I can place a script directly on the CharacterController component to detect this (nor do I know how I would filter such collisions out from normal ones) and detecting a collision with the character controller component from within this script doesn’t appear to be possible. Any thoughts on how I can go about solving this dilemma?