Upcoming Events
VIEW Conference 2009
11/4 - 11/7 @ Turin, Italy

Project Horseshoe
11/5 - 11/8 @ Burnet, TX

Independent Game Conference West
11/5 - 11/6 @ Los Angeles, CA

IGDA Leadership Forum
11/12 - 11/13 @ San Francisco, CA

More events...


Quick Stats
7012 people currently visiting GDNet.
2337 articles in the reference section.

Help us fight cancer!
Join SETI Team GDNet!



Link to us

Link to us

  search:   

Normalizing a quaternion

Normalizing a quaternion is almost the same as normalizing a vector. We start by computing the length of the quaternion to be normalized, which is done using the Euclidean distance forumula:

|Q| = sqrt( w^2 + x^2 + y^2 + z^2)

A function to implement this formula might look like this:

double length(quaternion quat)
{
  return sqrt(quat.x * quat.x + quat.y * quat.y +
              quat.z * quat.z + quat.w * quat.w);
}

Not too hard is it? Now to get the normalized vector Q, which we'll call Q*, we just divide every element of Q by |Q|.

Q* = Q/|Q| = [w/|Q|, v/|Q|]

Here's some sample code for this function:

quaternion normalize(quaternion quat)
{
  double L = length(quat);

  quat.x /= L;
  quat.y /= L;
  quat.z /= L;
  quat.w /= L;

  return quat;
}

This will give us a quaternion of length 1 (which is very important for rotations). Still nothing scary right? Well, it doesn't really get much harder than this.

The conjugate of a quaternion

Let's compute the conjugate of a quaternion and call it Q'. The conjugate is simply

Q' = [ w, -v ]

Here's the code for the conjugate:

quaternion conjugate(quaternion quat)
{
  quat.x = -quat.x;
  quat.y = -quat.y;
  quat.z = -quat.z;
  return quat;
}

The last thing you need to know is quaternion multiplication. Then you'll be ready to make a quaternion based camera.

Multiplying quaternions

Multiplication with quaternions is a little complicated as it involves dot-products cross-products. However, if you just use the following forumula that expands these operations, it isn't too hard. To multiply quaternion A by quaternion B, just do the following:

C = A * B

such that:

C.x = | A.w*B.x + A.x*B.w + A.y*B.z - A.z*B.y |
C.y = | A.w*B.y - A.x*B.z + A.y*B.w + A.z*B.x |
C.z = | A.w*B.z + A.x*B.y - A.y*B.x + A.z*B.w |
C.w = | A.w*B.w - A.x*B.x - A.y*B.y - A.z*B.z |

Here's some code for multiplication:

quaternion mult(quaternion A, quaternion B)
{
  quaternion C;

  C.x = A.w*B.x + A.x*B.w + A.y*B.z - A.z*B.y;
  C.y = A.w*B.y - A.x*B.z + A.y*B.w + A.z*B.x;
  C.z = A.w*B.z + A.x*B.y - A.y*B.x + A.z*B.w;
  C.w = A.w*B.w - A.x*B.x - A.y*B.y - A.z*B.z;
  return C;
}

That's not too that hard is it? Now we'll look at how to use these operations to make a quaternion based camera.



The Quaternion Camera

Contents
  Introduction
  Quaternion Operations
  The Quaternion Camera

  Printable version
  Discuss this article