Welcome to the Second Life Forums Archive

These forums are CLOSED. Please visit the new forums HERE

dot product problem

Kayaker Magic
low carbonated footprint
Join date: 11 Sep 2008
Posts: 109
02-22-2009 15:39
I want the angle between two arbitrary vectors, so I used the dot product to find it.
Problem is, it never returns angles >180 or <0. Here's a sample script:

float dot(vector a,vector b)
{
return (a.x*b.x+a.y*b.y+a.z*b.z);
}
default
{
state_entry()
{
rotation rot=llEuler2Rot(<0,0,10.*DEG_TO_RAD>;); //rotate in 10 degree steps
vector vec=<10.,0.,0.>; //start with any vector at 0 degrees
integer i;
for (i=10;i<=360;i+=10) //just a loop counter, no math using i
{
vec=vec*rot; //rotate 10 more degrees
//convert back to degrees from vector
float theta=llAcos(dot(vec,<1.,0.,0.>;)/llVecMag(vec))*RAD_TO_DEG;
llOwnerSay((string)vec+" angle="+(string)theta);
} //for
} //state_entry

} //default


The angle is supposed to increase from 10 to 360 degrees, but it increases to 180 and then starts back down again. In this case, I could check the sign of vec.y and flip the sign of the angle, but this only works when the second vector is on the X axis. How do I do that for two arbitrary angles?
Pedro McMillan
SLOODLE Developer
Join date: 28 Jul 2007
Posts: 231
02-22-2009 15:54
I'm afraid you've misunderstood the geometry a little. (Don't worry... easily done...)

Smallest angle between 2 vectors is always 0 degrees... i.e. facing the same way... so negative angles are not possible. And the biggest angle between 2 vectors is 180 degrees... i.e. facing opposite directions.

It's easier to imagine in 2 dimensions, so think about the face of a clock, where the hour hand is always pointing directly upwards at 12 (it never moves), and the minute hand rotates around clockwise. When the minute hand hits 3, the angle between the hands is 90 degrees. When it hits 6, the angle is 180 degrees. And when it hits 9, the angle is 90 degrees again.

Basically, the dot product figures out the smallest angle between two vectors. When it comes to 3d stuff though, the maths gets pretty complicated when handling angles (hence the use of quaternions). If you can simplify your problem down to 2 dimensions, then it's much easier to figure out the information you want using fairly straightforward geometry.
Hewee Zetkin
Registered User
Join date: 20 Jul 2006
Posts: 2,702
02-22-2009 19:53
By the way, in LSL the normal multiplication operator (*) takes a dot product when the factors are two vectors. So 'vecA*vecB' is a float that is equal to the dot product of vector vecA and vector vecB.