I have added an ability to crouch in the game. The way I've done that is by changing the controller height and center y value. The issue is when I crouch to go underneath a platform the player still collides with the platform even though there's clearly enough space.
If I set the controller height to the crouch height as the default height the player is able to go underneath the platform without trouble. Although, if I use the center offset the collision issue occurs.
bool isCrouching; float defaultHeight; Vector3 localCameraPos;
private CharacterController controller = null;
private Camera camera;
void Start()
{
controller = GetComponent<CharacterController>();
camera = camera.main;
localCameraPos = camera.transform.localPosition;
defaultHeight = controller.height;
}
void Update()
{
isCrouching = Input.GetKey(KeyCode.C);
}
void FixedUpdate()
{
DoCrouch();
}
void DoCrouch()
{
var height = isCrouching ? defaultHeight / 2 : defaultHeight;
controller.height = Mathf.Lerp(controller.height, height, 5 * Time.deltaTime);
controller.center = Vector3.down * (defaultHeight - controller.height) / 2.0f;
var camPos = new Vector3(0, camera.transform.localPosition.y, 0);
camPos.y = Mathf.Lerp(camPos.y, localCameraPos.y - (defaultHeight - controller.height), 5 * Time.deltaTime);
camera.transform.localPosition = camPos + localCameraPos;
}
The player moves by calling CharacterController.move() function.
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
isWalking = !Input.GetKey(KeyCode.LeftShift);
Vector2 _inputVector = new Vector2(horizontal, vertical);
if (_inputVector.sqrMagnitude > 1) { _inputVector.Normalize(); }
Vector3 desireMoveDir = transform.right * _inputVector.x;
desireMoveDir += transform.forward * _inputVector.y;
if (Physics.SphereCast(transform.position, controller.radius, Vector3.down, out RaycastHit hit, controller.height / 2f, 1))
{
desireMoveDir = Vector3.ProjectOnPlane(desireMoveDir, hit.normal).normalized;
}
moveDirection = desireMoveDir * MoveSpeed;
controller.Move(moveDirection * Time.fixedDeltaTime);
}
How do I fix this issue? Thank you