Search Unity

Preventing Z rotation change

Discussion in 'Scripting' started by Josiah_Ironclad, Feb 1, 2020.

  1. Josiah_Ironclad

    Josiah_Ironclad

    Joined:
    Sep 24, 2019
    Posts:
    156
    I took some code from a platformer tutorial series for an orbiting camera.

    The camera rotates a pivot object, and moves based on that rotation and an offset vector.
    Code (CSharp):
    1. // Get the X position of the mouse & rotate the pivot
    2. horizontalRotation = Input.GetAxis("Mouse X") * horizontalSensitivity;
    3. pivot.Rotate(0, horizontalRotation, 0);
    4.  
    5. // Get the Y position of the mouse & rotate the pivot
    6. verticalRotation = Input.GetAxis("Mouse Y") * verticalSensitivity;
    7. pivot.Rotate(-verticalRotation, 0, 0);
    8.  
    9. float desiredXAngle = pivot.eulerAngles.x;
    10. float desiredYAngle = pivot.eulerAngles.y;
    11.  
    12. Quaternion rotation = Quaternion.Euler(desiredXAngle, desiredYAngle, 0);
    13. transform.position = target.position + (rotation * offset);
    14.  
    15. transform.LookAt(target);
    When I move the camera around, the Z rotation of the pivot is being changed. I know this is happening because of eulers, but I don't remember how to fix it.

    Looked around the internet, but found nothing so far. I've had this problem a lot in the past, and most of the time I fixed it, but I either didn't document it, or have long since deleted the files.
     
    Last edited: Feb 1, 2020
  2. diXime

    diXime

    Joined:
    Oct 2, 2018
    Posts:
    162
    Hello,
    It's your LookAt, I'd say. Try to use transform.rotation = rotation instead?
     
  3. Josiah_Ironclad

    Josiah_Ironclad

    Joined:
    Sep 24, 2019
    Posts:
    156
    It's not, the camera is fine in terms of rotation, it's the pivot object's Z that changes, causing the camera movement to act weird after some time rotating.