User:Pedro Oval/Calculate rotation for pointing in a direction

From Second Life Wiki
< User:Pedro Oval
Revision as of 20:47, 7 January 2011 by Pedro Oval (talk | contribs) (Expand text, add authorship comment)
Jump to navigation Jump to search

Here are two functions that, given a vector to point at, return the rotation that corresponds to that vector.

The first function, PointAt2Rot, makes the forward (X) vector point exactly in that direction, while keeping the up (Z) vector pointing "as up as possible". It is similar to what llLookAt does, except that the vector that points to the target is X (forward) instead of Z (up), and the result is a rotation, not a continuously updating state of pointing in the given direction.

The second function, PointAtHoriz2Rot, points to the horizontal that is closest to the given vector, while the up vector points exactly up. It is useful if the final resulting rotation must be horizontal.

Note that both functions have trouble handling the case where the target is directly above or below the source, and in that case the resulting rotation might be wrong.

<lsl> // Written by Pedro Oval, 2011-01-08

rotation PointAt2Rot(vector target) {

   vector fwd = llVecNorm(target);
   vector left = llVecNorm(<0., 0., 1.> % fwd);
   vector up = fwd % left;
   return llAxes2Rot(fwd, left, up);

}

rotation PointAtHoriz2Rot(vector target) {

   vector up = <0., 0., 1.>;
   vector left = llVecNorm(up % target);
   vector fwd = left % up;
   return llAxes2Rot(fwd, left, up);

} </lsl>