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;
}
}
}