Search Unity

Question Trying to refactor character controller help

Discussion in 'Scripting' started by daqid, Mar 20, 2023.

  1. daqid

    daqid

    Joined:
    Sep 21, 2018
    Posts:
    1
    i've been struggling trying to refactor my character controller into a HandleRotation() and HandleMovement() function. i'm using the new input system, _getMovementInput is reading a vector 2 from the input assets. adding a controller.move(moveDir * Time.DeltaTime) into my handleMovement() function works but because "targetAngle" is in the y, i loose my gravity. i have a vector 3 "_moveDirection" that is set to _getMovementInput.x, 0, _getMovementInput.y and if i pass that in i get my gravity back but loose the ability to turn with the camera.

    Code (CSharp):
    1. private void HandleRotation()
    2.     {
    3.         Vector3 direction = new Vector3(_getMovementInput.x, 0, _getMovementInput.y);
    4.  
    5.         if (IsMovementPressed)
    6.         {
    7.          
    8.             targetAngle = (float)(Math.Atan2(direction.x, direction.z) * Mathf.Rad2Deg) + cam.eulerAngles.y;
    9.             float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
    10.             transform.rotation = Quaternion.Euler(0f, angle, 0f);
    11.  
    12.             moveDir = Quaternion.Euler(0, targetAngle, 0) * Vector3.forward;
    13.          
    14.         }
    15.     }
    Code (CSharp):
    1. private void Move_started(InputAction.CallbackContext obj)
    2.     {
    3.        
    4.         _getMovementInput = obj.ReadValue<Vector2>();
    5.         _moveDirection.x = _getMovementInput.x;
    6.         _moveDirection.z = _getMovementInput.y;
    7.         _isMovementPressed = _getMovementInput.x != 0 || _getMovementInput.y != 0;
    8.  
    9.     }