can you write a code to transform euler angles into quaternions? in javascript

Here is a code snippet in JavaScript to transform Euler angles into quaternions:

index.tsx
function eulerToQuaternion(roll, pitch, yaw) {
  // Convert Euler angles to radians
  var phi = roll * Math.PI / 180;
  var theta = pitch * Math.PI / 180;
  var psi = yaw * Math.PI / 180;

  // Calculate quaternion values
  var cy = Math.cos(psi * 0.5);
  var sy = Math.sin(psi * 0.5);
  var cr = Math.cos(phi * 0.5);
  var sr = Math.sin(phi * 0.5);
  var cp = Math.cos(theta * 0.5);
  var sp = Math.sin(theta * 0.5);

  var w = cy * cr * cp + sy * sr * sp;
  var x = cy * sr * cp - sy * cr * sp;
  var y = cy * cr * sp + sy * sr * cp;
  var z = sy * cr * cp - cy * sr * sp;

  return [w, x, y, z];
}

// Example usage
var eulerAngles = [30, 45, 60]; // Roll, pitch, and yaw angles in degrees
var quaternion = eulerToQuaternion(eulerAngles[0], eulerAngles[1], eulerAngles[2]);
console.log(quaternion);
802 chars
27 lines

It converts the Euler angles (roll, pitch, and yaw) provided as input into quaternions. The resulting quaternion is an array [w, x, y, z] where w represents the scalar component and x, y, and z represent the vector components of the quaternion.

gistlibby LogSnag