Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question Why is my camera accumulating difference on rotation?

Discussion in 'Input System' started by gustavomedeiros_unity, Jan 17, 2024.

  1. gustavomedeiros_unity


    Aug 11, 2023
    Kind of solved:
    In my head the old solution made perfect sense, and still does to be honest. Due to how small the imprecision was and how much it needed to accumulate to be noticeable, I suspect (albeit with no proof) it was caused by float imprecision.

    The solution that worked for me was storing the last walk input from the player in the input class to be available at all times. This way the rotation is made relative to the fresh input direction, not by vectors that had been transformed many times, possibly accumulating float imprecisions.

    First of all, sorry for bothering you guys. This is my first time using unity (only had very little experience in pygame) and I've been following a few tutorials for the past days, but found some problems.

    I'm trying to implement a first person character controller using the new input system and cinemachine.
    My solution seemed to work, but I noticed that when walking while rotating the camera, the character rotation and movement direction are having a very small desynchronization that accumulates over time.
    If I press W and rotate my camera aggressively, the rotation differences can be so big that the character may move backwards while the camera faces forward. I've been debugging the code for this for a couple of days and couldn't find the issue.

    Video of me pressing only W and rotating the camera, causing the movement to go in the wrong direction instead of forward.

    I have a camera manager class, a player movement management class and a input manager class.
    In my current project structure, the input manager calls the player movement and camera manager classes when their respective actions are detected by the new input system.

    This is the call flow for when the player moves the mouse:
    Code (CSharp):
    1. void OnMoveCameraPerformed(InputAction.CallbackContext context)
    2.         {
    3.             Vector2 cameraInput = context.ReadValue<Vector2>();
    4.             Vector3 oldProjectedCameraForward = cameraManager.activeCamera.transform.forward;
    6.             cameraManager.RotateFromInput(cameraInput);
    8.             // adjust the walk direction to match the direction the player is looking at (very likely where the problem resides)
    9.             if (!_playerMovement.IsWalking)
    10.                 return;
    12.             oldProjectedCameraForward.y = 0f;
    13.             oldProjectedCameraForward.Normalize();
    15.             Vector3 newProjectedCameraForward = cameraManager.activeCamera.transform.forward;
    16.             newProjectedCameraForward.y = 0f;
    17.             newProjectedCameraForward.Normalize();
    18.             _playerMovement.NextWalk = Quaternion.FromToRotation(oldProjectedCameraForward, newProjectedCameraForward)
    19.                                        * _playerMovement.NextWalk;
    20.         }
    Assuming nextwalk is not, then the player is already moving towards a direction. I hope this little sketch clarifies:
    So, what the
    Quaternion.FromToRotation(oldProjectedCameraForward, newProjectedCameraForward) * _playerMovement.NextWalk;
    line is trying to do is get the rotation from the red to the purple vector, and applying it to the blue one.

    Code (CSharp):
    1.     public override void RotateFromInput(Vector2 horizontalVerticalInput)
    2.     {
    3.         // input treatment
    4.         float horizontalRotationDelta =
    5.             horizontalVerticalInput.x * Time.deltaTime * _defaultMultiplier * mouseSensitivity;
    6.         float verticalRotationDelta =
    7.             -horizontalVerticalInput.y * Time.deltaTime * _defaultMultiplier * mouseSensitivity;
    9.         // adding to class rotation and clamping it. (rotation saved in class so that it's easier to clamp and not let the player do a 360 with the vertical camera rotation)
    10.         _verticalRotation += verticalRotationDelta;
    11.         _verticalRotation = Mathf.Clamp(_verticalRotation, -90f, 90f);
    12.         _horizontalRotation += horizontalRotationDelta;
    14.         // Setting the new rotation from class rotation.
    15.         Vector3 newRotation = new Vector3(_verticalRotation, _horizontalRotation, 0f);
    17.         transform.localEulerAngles = newRotation;
    18.         playerTransform.localEulerAngles += new Vector3(0f, horizontalRotationDelta, 0f);
    19.     }

    This is the flow for when the player presses WASD:

    Code (CSharp):
    1.         void OnWalkPerformed(InputAction.CallbackContext context)
    2.         {
    3.             Vector3 walkInput = context.ReadValue<Vector3>();
    4.             Vector3 projectedCameraForward = cameraManager.mainCamera.transform.forward;
    5.             projectedCameraForward.y = 0f;
    6.             projectedCameraForward.Normalize();
    7.             Vector3 walkDirection = Quaternion.FromToRotation(Vector3.forward, projectedCameraForward) * walkInput;
    8.             _playerMovement.WalkTowards(walkDirection);
    9.         }
    If I understood the input system correctly correctly, this is only called if the player changes the WASD vector, which means it will only be called the first time.
    Consequently, rotating the camera will not automatically change the player's movement direction, which is why in the camera rotating code I try to rotate the walk vector accordingly. (probably where the bug resides)

    Code (CSharp):
    1.         public void WalkTowards(Vector3 direction)
    2.         {
    3.             NextWalk = _walkSpeed/_accelerationTimeSeconds * direction;
    4.         }
    (note that this sort of schedules the walk instead of applying it immediately. this is because the actual motion is applied only on the next fixedupdate, aiming to follow the recommendation of only doing physics stuff on fixedupdate)

    The flow of the playermovement's fixedUpdate:

    Code (CSharp):
    1.         public void FixedUpdate()
    2.         {
    3.             ApplyWalk();
    4.             Move();
    5.         }

    Code (CSharp):
    1.         private void ApplyWalk()
    2.         {
    3.             if (NextWalk ==
    4.             {
    5.                 Vector3 brakeVector = walkVelocity.normalized * _walkSpeed / _accelerationTimeSeconds;
    6.                 // if the brake vector is bigger than the velocity vector, set to avoid going backwards.
    7.                 if (brakeVector.magnitude > walkVelocity.magnitude)
    8.                 {
    9.                     walkVelocity =;
    10.                     return;
    11.                 }
    12.                 walkVelocity -= brakeVector;
    13.                 return;
    14.             }
    15.             walkVelocity += NextWalk;
    16.             if (walkVelocity.magnitude >= _walkSpeed)
    17.             {
    18.                 walkVelocity = walkVelocity.normalized* _walkSpeed;
    19.             }
    20.         }

    Code (CSharp):
    1. private void Move()
    2.         {
    4.             _hitbox.MovePosition(transform.position + (_playerVelocity + walkVelocity) * Time.fixedDeltaTime);
    5.         }
    Last edited: Jan 17, 2024
  2. halley


    Aug 26, 2013
    So, welcome to the forum. This is your first post. You win the "Best Formatted First Post" and "Most Thorough First Post" award for the year. Maybe for the past decade.

    I don't have a complete understanding of your code, but this below is a code smell to me. You're setting the camera's rotation explicitly, but you're turning the player's rotation by a delta. If you want your camera and player to always be in sync, then either set them both explicitly, or set one explicitly from the other after it has been adjusted.

    Code (CSharp):
    1. transform.localEulerAngles = newRotation;
    2. playerTransform.localEulerAngles += new Vector3(0f, horizontalRotationDelta, 0f);
    Definitely pepper your code with Debug.Log() and study the interplay of variables, if you can't just single-step through with a debugger. It might be something about crossing a 360/0 barrier on your angles or something simple like that.

    In terms of learning the API, you may be interested in Vector3.ProjectOnPlane(), and Vector3.ClampMagnitude(). Doing it your way works, but can be less readable or maintainable if you later use your code in different situations.
  3. gustavomedeiros_unity


    Aug 11, 2023
    Well thank you very much haha. I know from trying to help friends on college how mentalizing other people's logic can be hard.. in the end I'm trying to help you guys help me XD.

    I'll definitely test your suggestions and points and update the post, thanks.
  4. gustavomedeiros_unity


    Aug 11, 2023
    I found a kind of unrelated solution, but your answer made me learn a bunch of new stuff and put me in the right track. Thank you!