Sorry your browser is not supported!

You are using an outdated browser that does not support modern web technologies, in order to use this site please update to a new browser.

Browsers supported include Chrome, FireFox, Safari, Opera, Internet Explorer 10+ or Microsoft Edge.

Code Snippets / [DBP] - Get angle between two vectors

Author
Message
Phaelax
DBPro Master
21
Years of Service
User Offline
Joined: 16th Apr 2003
Location: Metropia
Posted: 29th Sep 2013 01:00 Edited at: 17th Oct 2013 11:16
I've seen this asked a few times, I think I've wanted to know myself before as well. It wasn't until I saw the equation to find the dot product that I realized how easy it was to figure out.

|A| * |B| * cos(a)

The lengths of vectors A and B multiplied together along with the cosine of the angle between them equals the dot product. But the simpler way to calculate the dot product is:

A.x * B.x + A.y * B.y


Put two and two together and I get the method shown below. Here's a quick demo. Use the mouse buttons to change the vectors.



Silverman
17
Years of Service
User Offline
Joined: 18th Jan 2007
Location: France
Posted: 12th Oct 2013 15:48 Edited at: 12th Oct 2013 15:48
hi,

Quote: "A.x * B.x + A.y + B.y"


you meant to say:

A.x * B.x + A.y * B.y

DirectX 9.0c (February 2010)/ DBClassic v1.20
Le Verdier
12
Years of Service
User Offline
Joined: 10th Jan 2012
Location: In the mosh-pit
Posted: 12th Oct 2013 19:28 Edited at: 12th Oct 2013 19:41
This is too much complicated, and there is a hidden issue with this method..
I advise this instead:


The lentghs are not needed.
With Acos, numerical inacuracies can occur
And dp# / (Alen#*Blen#) cannot handle len#=0.0

Phaelax
DBPro Master
21
Years of Service
User Offline
Joined: 16th Apr 2003
Location: Metropia
Posted: 18th Oct 2013 08:18
Yes Silverman, thanks for the correction. A slight typo on my part.

Le Verdier, at first glance I would agree your method is better since I can skip the calculation on the vector lengths. But even though mine uses acos, yours is still using atanfull which internally would use atan in its calculations anyway. So any inaccuracies found in acos would surely be present in atan as well.

Login to post a reply

Server time is: 2024-11-21 15:55:48
Your offset time is: 2024-11-21 15:55:48