Angle Measured in Degrees Bug(Trigonometry)

Good evening. I am currently trying to find the relative angle between two Game Objects by calculating the inverse tangent of the variable slope of the two position vectors. It seems to be working, except for the fact that the angle jumps from 90 to 270. I don’t think there’s anything wrong with my equations but after hours of messing with it, I can’t seem to find the cause. I also get the same result when I calculate the inverse sine of the two vectors.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpriteBillboardShader : MonoBehaviour
{
        public Animator objectAnimator;
        public GameObject cameraParent;
        private Vector3 localPosition;
        private Vector3 cameraPosition;
        private float localX;
        private float localZ;
        private float cameraX;
        private float cameraZ;
        public float slope;
        public float angle;
        private int directions = 8;

        void awake(){
        }

        void Start(){
            cameraParent = GameObject.Find("Player");

        }

        void Update(){

            //Slope Calculation\\
        localPosition = gameObject.transform.position;
            localX = localPosition.x;
                localZ = localPosition.z;

            cameraPosition = cameraParent.transform.position;
                cameraX = cameraPosition.x;
                cameraZ = cameraPosition.z;

        slope = (cameraZ - localZ)/(cameraX - localX);

        angle = Mathf.Rad2Deg * Mathf.Atan(slope);

        if (angle < 0){
            angle = 360 + angle;
        }

        }
}

I haven’t looked carefully at your particular use-case, but if your code is mixing up 90 and 270 degrees, that sounds like it’s probably an issue with using Atan() instead of Atan2().

Atan() only covers an output range of 180 degrees, because it only looks at slope, and slope can’t distinguish between quadrants 1 and 3 (positive/positive vs negative/negative) or between quadrants 2 and 4 (positive/negative vs. negative/positive). For instance, 0 degrees and 180 degrees both have a slope of zero, or 45 degrees and 225 degrees both have a slope of 1.

For this reason, it is usually better to use Atan2() instead, which accepts X and Y as separate parameters, and so can distinguish a full 360 degree range. (It also protects you from divide-by-zero errors.)

1 Like

Thank you, that worked perfectly. Although I completely understand that this is out of reach with this equation, would there be any easy way to make the angle not be dependent on the distance between the two objects? I’d like for the angle to remain the same regardless of the distance but I know that’s impossible with this calculation due to the slope corresponding with the vector values.

In what sense do you believe the angle is dependent on the distance?