Search Unity

[UI Help] How to keep look at but with anti roll on phone

Discussion in 'Scripting' started by MikeSorokin, Jan 17, 2021.

  1. MikeSorokin

    MikeSorokin

    Joined:
    Jan 17, 2021
    Posts:
    1
    Basically what I want is to have the camera always look at the camera which can be achieved with the following LookAt rotation code:


    Code (CSharp):
    1.         transform.LookAt(transform.position + Camera.main.rtansform.rotation * Vector3.forward,
    2.             Camera.main.rtansform.rotation * Vector3.up);
    3.  
    HOWEVER, I want this to ALSO stay in place even when the phone rolls about itself 90 degrees. The problem is the pitch flips around 90 degrees, which doesn't allow the look at to be proper when the phone is looking directly at the UI.

    My code to attempt this is:

    Code (CSharp):
    1.         // 180 about z (roll) in order to counter the phone's rotation
    2.         Quaternion antiRoll = Quaternion.Euler(camRotation.eulerAngles.x, camRotation.eulerAngles.y, 180f);
    3.  
    4.         Quaternion savedRot;
    5.         // The above was almost good, but we have to flip rot upside down AND backwards in world space
    6.         // in order to get it in proper world space
    7.         savedRot = antiRoll * Quaternion.Euler(180f, 180f, 0);
    8.  
    9.         transform.LookAt(transform.position + targetTransform.rotation * Vector3.forward,
    10.             savedRot * Vector3.up);
    11.  

    I guess my questions are:

    (1) - Why does this happen? Gimbal lock? Can anyone explain in depth.
    (2) - I feel as if this is close, do I need to combine rotations or something?

    Video showing problem when the pitch gets past 90 degrees:
     
  2. TheOtherUserName

    TheOtherUserName

    Joined:
    May 30, 2020
    Posts:
    136
    I know what you are trying to say here but I also understand your problem with the 90 degree angle. It looks like your UI can rotate over 90 degrees on the X-axis. maybe clamp it between - 90and 90 would help. but I have not tried doing something like that so I might as well be wrong with this one.