Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Problem when rotating two axes simultaneously

Discussion in 'Physics' started by homanicsjake, Aug 7, 2019.

  1. homanicsjake

    homanicsjake

    Joined:
    Feb 18, 2019
    Posts:
    15
    Hello! So I have a problem where when rotating a Transform on two axes simultaneously causes the third axes to be rotated also.

    Code (CSharp):
    1. public class RotationManager : MonoBehaviour
    2. {
    3.     private Quaternion _targetRot;
    4.  
    5.     public RangeFloat xClamp = new RangeFloat(-360f, 360f);
    6.     public RangeFloat yClamp = new RangeFloat(-360f, 360f);
    7.     public RangeFloat zClamp = new RangeFloat(-360f, 360f);
    8.  
    9.     private void Start()
    10.     {
    11.         _targetRot = transform.localRotation;
    12.     }
    13.  
    14.     private void Update()
    15.     {
    16.         transform.localRotation = _targetRot;
    17.     }
    18.  
    19.     public void AddEulerAngles(Vector3 vector)
    20.     {
    21.         _targetRot *= Quaternion.Euler(vector);
    22.     }
    23.  
    24.     public void AddQuaternion(Quaternion quaternion)
    25.     {
    26.         _targetRot = quaternion * _targetRot;
    27.     }
    and
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class GunRecoil : MonoBehaviour
    6. {
    7.     public RotationManager rotationManager;
    8.     public float xRecoil = 5f;
    9.     public float yRecoil = 1f;
    10.  
    11.     void Update()
    12.     {
    13.         if (Input.GetButtonDown("PrimaryAction"))
    14.         {
    15.             rotationManager.AddEulerAngles(new Vector3(yRecoil, xRecoil, 0));
    16.         }
    17.     }
    18. }
    19.  
    Maybe my approach isn't correct? I am trying to make a system where you can have the mouse look and the recoil affect the rotation of the camera. In all the examples and tutorials, using their approach, one script would override the rotation of another. The mouse look script (not attached) works as intended. As does the recoil. But when I try to rotate two axes at once, it will rotate the third. In this case the Z axis.

    Any help would be appreciated. Thanks :)
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    It's called gimbal lock, look it up.

    You can use quaternion, two transforms(one for X, one for Y) or manually keeping track of the euler angles to solve the issue.