x


Calculate the angle between two 3d vectors: Function always returns 89.1-89.9

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) );
}
more ▼

asked Aug 17 '12 at 09:04 AM

gretty gravatar image

gretty
1 1 2 3

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

Do you know that Unity already provide such methods? Vector3.Angle

Anyway there is something wrong in your formula because you use squared magnitude instead of magnitude. The angle between two vectors is:

angle = acos(v1.v2/(||v1||*||v2||))

where . is the dot product and ||v|| is the magnitude of the vector v.

But like I said, all methods are already provided by Unity. See the reference for Vector3.

more ▼

answered Aug 17 '12 at 09:07 AM

Kryptos gravatar image

Kryptos
7.2k 5 33

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1072
x21

asked: Aug 17 '12 at 09:04 AM

Seen: 629 times

Last Updated: Aug 17 '12 at 09:10 AM