Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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. enter image description here

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
144 views
Welcome To Ask or Share your Answers For Others

1 Answer

Well just solved the problem. I had a step offset set to 0.7. Changing it to 0, fixed the problem. Only took me two days...nice


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...