## LSL Wiki : Quaternions

HomePage :: PageIndex :: RecentChanges :: RecentlyCommented :: UserSettings :: You are crawl338.us.archive.org

## Quaternions

(continued from rotation)

To set the elements of the rotation type directly, compute the quaternion as follows. To represent a rotation of a given angle around a given axis, first, convert the axis to a unit vector (a vector of magnitude 1). Take the x, y, and z components of the unit vector and multiply them by the sine of half the angle (these are the x, y, and z elements of the quaternion). The s element of the quaternion is equal to the cosine of half the angle.

The following function performs this in LSL:

```rotation make_quaternion( vector axis, float angle )
{
vector unit_axis = llVecNorm( axis );
float sine_half_angle = llSin( angle/2 );
float cosine_half_angle = llCos( angle/2 );

rotation quat;
quat.x = sine_half_angle * unit_axis.x;
quat.y = sine_half_angle * unit_axis.y;
quat.z = sine_half_angle * unit_axis.z;
quat.s = cosine_half_angle;

return quat;
}```

This example duplicates the function llAxisAngle2Rot. Note that the angle must be specified in radians rather than degrees.

For a rotation around just the x-axis, the quaternion becomes simpler to compute, because in this case the unit axis is <1,0,0>:

rotation x_rot = <llSin( angle/2 ), 0, 0, llCos( angle/2 )>; // rotate around x-axis

Similarly, a rotation around just the y-axis or just the z-axis is also simpler to compute:

rotation y_rot = <0, llSin( angle/2 ), 0, llCos( angle/2 )>; // rotate around y-axis
rotation z_rot = <0, 0, llSin( angle/2 ), llCos( angle/2 )>; // rotate around z-axis

Rotation by 90 degrees can be further simplified:

rotation x_rot = <1, 0, 0, 1>; // rotate 90 degrees around x-axis
rotation y_rot = <0, 1, 0, 1>; // rotate 90 degrees around y-axis
rotation z_rot = <0, 0, 1, 1>; // rotate 90 degrees around z-axis

A rotation of angle 0 around any axis is represented the same way. Consider that the sine of 0 is 0, while the cosine of 0 is 1. As a result, no matter what axis is chosen, the null rotation is equal to <0,0,0,1>.

To find the inverse of a rotation, negate the last element of the quaternion:

inverse_quat = quat;
inverse_quat.s = -quat.s;

To find the inverse, negate the first 3 elements:

inverse_quat = < -quat.x, -quat.y, -quat.z, quat.s >;

If you negate all 4 elements of a quaternion, you end up with the same effective rotation.