X rotation of gameObject

I need to get the rotation of the game object relative to the global coordinate system. I need to get the range [0, 180] and [-180,0]. But I get the following values:[0; -90] in the first quarter, [0-90] in the second, [90;0] in the third and [-90; 0] in the fourth.

This is confusing me, I would be very grateful if you could help me find a solution

 [SerializeField] private TextMeshProUGUI _text;

    private void Update()
    {
        _text.text = $"<color=red>X:{Math.Round(ClampAngle(transform.eulerAngles.x), 2)}</color>| ";
    }
   
    float ClampAngle(float a) =>
        (a > 180) ? a - 360 : a;
}

It’s because Euler Angles can be represented by multiple different angles. The actual rotation of the object is not stored as a Euler, it is stored as a Quaternion and turned into a Euler. Even if you set the Euler Angle of an object, it may be given back to you as a different Vector3.

If you want an angle in the range of [-180, 180] around some particular axis you can use https://docs.unity3d.com/ScriptReference/Vector3.SignedAngle.html

1 Like

Thanks for the advice!

I solved it by this method:

private static float AngleOffAroundAxis(Vector3 v, Vector3 forward, Vector3 axis, bool clockwise = false)
    {
        Vector3 right;
        if(clockwise)
        {
            right = Vector3.Cross(forward, axis);
            forward = Vector3.Cross(axis, right);
        }
        else
        {
            right = Vector3.Cross(axis, forward);
            forward = Vector3.Cross(right, axis);
        }
        return Mathf.Atan2(Vector3.Dot(v, right), Vector3.Dot(v, forward)) * Mathf.Rad2Deg;
    }

I don’t really like that I have to change the coordinates of the target, following the object. But theoretically, if it is possible to move this from update to some event model, might work well

private void Update()
    {
        Vector3 pos = target.transform.position;
        pos.y = transform.position.y;
        pos.z = transform.position.z;
        target.transform.position = pos;
       
        Debug.Log(90 - AngleOffAroundAxis(target.transform.position - transform.position, transform.forward, Vector3.up));
    }