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

From Second Life Wiki
< User:Pedro Oval
Revision as of 05:36, 11 January 2011 by Pedro Oval (talk | contribs) (The division by llGetRot actually doesn't work so well; remove from the text)
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.

One of the functions, 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 other 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.

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

rotation PointAtHoriz2Rot(vector target) {

   // Find the Z rotation:
   return llRotBetween(<1., 0., 0.>, <target.x, target.y, 0.>);

}

rotation PointAt2Rot(vector target) {

   // Find the Z rotation:
   rotation r = PointAtHoriz2Rot(target);
   // Find the Y rotation and multiply it with the Z one:
   return llRotBetween(<1., 0., 0.>, target/r) * r;

} </lsl>

The following is a version of llPointAt2Rot that allows a viewup vector (the vector that determines the tilting) expressed in world coordinates:

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

rotation PointAtViewup2Rot(vector target, vector viewup) {

   vector fwd = llVecNorm(target);
   vector left = llVecNorm(viewup % target);
   vector up = fwd % left;
   return llAxes2Rot(fwd, left, up);

} </lsl>