Unity 3D Game Engine – Quaternions

In mathematics, the quaternions are a number system that extends the complex numbers. They were first described by Irish mathematician William Rowan Hamilton in 1843 and applied to mechanics in three-dimensional space.

According to Euler’s rotation theorem, any rotation or sequence of rotations of a rigid body or coordinate system about a fixed point is equivalent to a single rotation by a given angle θ about a fixed axis (called Euler axis) that runs through the fixed point. The Euler axis is typically represented by a unit vector u→. Therefore, any rotation in three dimensions can be represented as a combination of a vector u→ and a scalar θ. Quaternions give a simple way to encode this axis–angle representation in four numbers, and to apply the corresponding rotation to a position vector representing a point relative to the origin in R3.

Unity utilizes the quaternion system to manage the rotation of game objects.

In Unity Quaternions have 4 componments: X Y Z W and they work together to define any rotations.

Look At

Inside Hierarchy create:

1. Sphere and attach MotionScript.js


#pragma strict

public var speed : float = 3f;


function Update () 
{
    transform.Translate(-Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0, 0);
}

2. Cube and attach LookAtScript.js


#pragma strict

public var target : Transform;

function Update () 
{
    var relativePos : Vector3 = target.position - transform.position;
    transform.rotation = Quaternion.LookRotation(relativePos);
}

Inspector> LookAtScript.js> DRAG AND DROP Sphere over var target

3. Play> Move the Sphere using keyboard arrow, the Cube will look at the Sphere

Gravity – Orbit

Inside Hierarchy create:

1. Sphere

2. Cube and attach GravityScript.js


#pragma strict

public var target : Transform;
    
    
function Update () 
{
    var relativePos : Vector3 = (target.position + new Vector3(0, 1.5f, 0)) - transform.position;
    var rotation : Quaternion = Quaternion.LookRotation(relativePos);
    
    var current : Quaternion = transform.localRotation;
    
    // Spherical Linear Interpolation
    transform.localRotation = Quaternion.Slerp(current, rotation, Time.deltaTime);
    transform.Translate(0, 0, 3 * Time.deltaTime);
}
 

Inspector> GravityScript.js> DRAG AND DROP Sphere over var target

3. Play> the Cube will rotate around the Sphere as a planet around the sun.