Hello
I have my own 2d game and I am attempting to calculate the angle between 2 GameObjects.
My Problem: My function that is meant to calculate the angle(direction) between 2 Vector3’s doesn’t appear to be correctly calculating the angle. It always returns a value thats between 89.1 and 89.9, its never any other value.
What am I doing wrong? Can you help me to get my function to correctly calculate the angle between 2 Vector3’s?
float getAngle(Vector3 p1, Vector3 p2) {
// If p1 or p2 == Vector3.zero then this funciton wont work. What shd I do in this case?
float coefI = p1.x * p2.x;
float coefJ = p1.y * p2.y;
float coefK = p1.z * p2.z;
float scalar = coefI + coefJ + coefK;
float magnitude1 = p1.sqrMagnitude;
float magnitude2 = p2.sqrMagnitude;
Debug.Log (System.String.Format ("{0}, {1}, {2}, {3}, {4}, {5}", coefI, coefJ, coefK, scalar, magnitude1, magnitude2));
return (Mathf.Acos ( scalar / (magnitude1 * magnitude2) ) * Mathf.Rad2Deg); // Always returns between 89.1 and 89.9 for some reason
}
void Update() {
Debug.Log( getAngle (Input.mousePosition, transform.position) );
}