Unity - Capsule Cast not working properly

42 Views Asked by At

I'm trying to use a capsule cast to prevent my player from moving through other game objects in unity. However, this only works for the front of the cube (what I'm using to test it) and even then doesn't always work.

This is my current code:

    private void HandleMovement() {
        
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");
        Vector3 forward = Camera.main.transform.forward;
        Vector3 right = Camera.main.transform.right;
        forward.y = 0;
        right.y = 0;
        forward = forward.normalized;
        right = right.normalized;

        Vector3 forwardRelativeInput = verticalInput * forward;
        Vector3 rightRelativeInput = horizontalInput * right;

        Vector3 relativeMovement = forwardRelativeInput + rightRelativeInput;
        transform.forward = forward;
        
        Vector3 translation = relativeMovement * Time.deltaTime * 7f;
        
        float playerHeight = 2f;
        float playerRadius = .5f;
        float moveDistance = translation.z;

        bool canMove = !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * playerHeight, playerRadius, translation, moveDistance);

        if(canMove) {
            transform.Translate(translation, Space.World);
        }
    }
0

There are 0 best solutions below