Unity Quaternion and Rotation Guide for beginners

Unity Quaternion may sound complex but it’s just another datatype like Vector3 that hold the rotation data of a Gameobject. In this tutorial, we are going to see how to use Quaternion effectively to perform rotations in Unity and how to rotate an object without Quaternion.

Unity quaternion blog post banner

What is a Quaternion in Unity?

Quaternion is a combination of a Vector3 and a scalar used to represent the rotation or orientation of an object.

The structure of quaternion looks like this (xi, yj, zk, w) where (xi, yj, zk) is a unit vector that represents the angle between the orientation and each individual axis. “w” represents the degree of rotation along the unit vector (xi, yj, zk).

In Unity, Quaternion can also be represented using a vector 4.

Quaternion vs Euler angles in Unity

The easier way to represent a rotation is using Euler Angles. A rotation in Euler Angles is basically the degree in each Axis (45,0,45).

There are certain limitations to Euler angles.

  1. Euler angles are subjected to Gimbal lock. It happens when two Axis align with each other and we lose one degree of freedom. Quaternion overcomes this limitation.
  2. In order to rotate a 3D object, you require a rotation matrix that increases the computational requirement. Quaternion represents rotation in just 4 numbers and is easy to be processed.

Unity allows you to specify Euler angles and save them to Quaternion. It’s discussed in the later part of this blog post.

Quaternion Example

Here is how Unity Displays Quaternion and Euler Angles for a Cube that has a rotation of (0,0,0)

Unity quaternion vs Euler example 1
Let’s change the rotation to 45,60,90 and see the result
Unity quaternion vs Euler example 2

Creating a new Quaternion

Quaternion is a Unity C# class. So, to create a new Quaternion, you need to create an object of the class and the syntax is shown below.

Quaternion newrotation = new Quaternion();

To set the value you can either give it while creating the new Quaternion like this

Quaternion newrotation = new Quaternion(0.9f,0.5f,0.6f,1);

or you can use Quaternion.Set

newQuaternion.Set(0.9f, 0.5f, 0.6f, 1);

How to rotate an Object in Unity

Like movement in Unity there are multiple ways to rotate an object in Unity. You can rotate an object using transform or you can create a simple animation or you can use Physics.

Rotation vs Rotate in Unity Quaternion

Many get confused between the transform.rotation and transfrom.rotate. Both these functions take in different values and produce different output.

transform.rotation takes a Quaternion and transform.rotate take a Vector3 with Euler angles.

“transform.rotate” adds the rotation to already existing values, whereas transform.rotation assigns the Quaternion value directly to the object’s rotation.

transform.rotation is used to set the rotation of a game object whereas transform.rotate is used to rotate an object by the given angle.

Transform Rotation syntax

transform.rotation=Quaternion

Transform rotate syntax

transform.rotate(Vector3)

Rotating an object using Euler Angles and transform.rotate

This is the most used method when you have to provide the rotation value manually.

Use a Vector3 to store the values of by which you want the object to rotate in each Axis and then pass them to “transform.rotate”.

Here is a code sample to rotate the object by 10 degrees in each axis. If the initial rotation is (20,20,20) then after the script has executed the object’s rotation will be (30,30,30).

using UnityEngine;

public class Rotation_demo : MonoBehaviour
{
    Vector3 rot=new Vector3(10,10,10);
  
    void Start()
    {
       transform.Rotate(rot);
        
    }
}

Set rotation of an object using Quaternion

It’s really difficult to know the quaternion value for rotation unless you are very familiar with the concept. But if you do know the value then you can create a new Quaternion and assign it to rotation of the object.

Remember none of the parameters of a Quaternion should be greater than 1. The values should be between (-1 to 1).

Here is a sample code

using UnityEngine;

public class lerp_demo : MonoBehaviour
{
    Quaternion rot=new Quaternion(0.4f,0.5f,0.9f,1);
  
    void Start()
    {
       transform.rotation=rot;
        
    }
}

The Above code will directly assign the rotation data to the Gameobject. You can convert Euler angles to Quaternion.

Rotating an Object using Physics

When your game uses Physics, it’s very important to use Physics forces on Rigidbody to rotate or it might break. To rotate an object, we need to use the rotation equivalent of force. It’s called Torque. The syntax to apply Torque in Unity is very similar to applying force.

Here is a sample code to apply an impulse Torque.

using UnityEngine;

public class rotation_example : MonoBehaviour
{
    public float torque;
    public Rigidbody rig;

    void Start()
    {
        rig = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        rig.AddTorque(transform.up * torque);
    }
}

Converting Vector3 to Quaternion

As mentioned earlier knowing the exact value of Quaternion is difficult for non-mathematicians. Unity provides a way to convert Euler angles saved as Vector3 to Quaternion.

Here is a simple example of how to assign a Vector3 to quaternion as Euler Angles.

using UnityEngine;
public class rotation_demo : MonoBehaviour
{
    Quaternion rot;
  
    void Start()
    {
        rot.eulerAngles=new Vector3(45,0,90);
    }
}

Convert Quaternion to Vector3

Similar to the above example you can also convert a Quaternion to Vector3. Any conversion between Quaternion and Vector3 includes Euler Angles.

You can extract the Euler angles from the quaternion and set them to a Vector3.

Here is a sample code

using UnityEngine;

public class test_script : MonoBehaviour
{
   Vector3 angle;
   Quaternion rotation_value;


   void Start()
   {
    rotation_value=transform.rotation;
    angle=rotation_value.eulerAngles;
    Debug.Log(angle);
   }
}

Now let’s see some examples scripts using quaternion in different scenarios.

Rotate by one Degree Every Frame

Now that you are clear with the concept of Unity Quaternion and Euler angles let’s see some examples. Let’s try to rotate an object by 1 degree every frame.

First you need a vector 3 with all three Axis values as 1.

We will use the Vector 3 as Euler angles and rotate the game object. Here is the code we are going to use

using UnityEngine;

public class rot_demo : MonoBehaviour
{
    Vector3 rot= Vector3.one;
  
    void Update()
    {
       transform.Rotate(rot);
        
    }
}

Here is the output of the above code

Cube rotating around its own axis at 1 degree/frame

You can also use Quaternion Lerp to slowly rotate an object over time.

Rotate an Object around a point

This is very useful for creating camera effects or Planetary motions.

You can rotate an object on its own axis using transform rotate but if you want to rotate an object around a different point and along a custom axis then this is for you.

We have two objects, a cube and a sphere, in our scene. Let’s rotate the cube around the sphere for the purpose of this tutorial.

We will be using transform.rotateAround for this purpose. It takes in 3 arguments.

The first one is a vector3 point in space around which you want the object to rotate. The second argument is the axis and the third one is the angular speed.

Syntax:

transform.RotateAround(Vector3 point, Vector3 axis, float angular_speed);

Let’s add the script below to our cube object. Make sure the sphere and the cube are not in the same position.

Select the cube and go to the Inspector window.

Click on add component and select new script.

Name the script as move_around

Copy and paste the code below into the script.

using UnityEngine;

public class move_around : MonoBehaviour
{
    public GameObject sphere;
    float angular_speed=20f;

    // Update is called once per frame
    void Update()
    {
        transform.RotateAround(sphere.transform.position,Vector3.up,angular_speed*Time.deltaTime);

        
    }
}

Here is the output

Cube rotating around a sphere along the vertical axis

If you change the axis from Vector3.up to Vector3.forward

The cube starts rotating around a different axis

Cube rotating around a sphere along the horizontal axis

Rotate an object to look in a particular direction using Quaternion.LookRotation

Unity Quaternion class has an inbuild function to make an object look in a particular direction. All you need to do, is to specify which direction to look at and what is the up axis along which the object needs to be rotated. The diagram below explains the concept.

If we want the above tank to look at the cube then here is code

using UnityEngine;


public class LookRotClass : MonoBehaviour
{
    public Transform cube;

    void Update()
    {
        Vector3 lookDir = cube.position - transform.position;

        // the second argument, upwards, defaults to Vector3.up which is (0,1,0). If this is not your object's upward direction, then you can use transform.up to get the upward direction of the object

        Quaternion rot = Quaternion.LookRotation(lookDir, transform.up);
        transform.rotation = rot;
    }
}

Rotating a 2D object in Unity

You can rotate a 2D object similar to a 3D object. You should only be sure of which axis you want to rotate the object in.

The default Unity 2D movement is along the X and Y axis. So, to rotate an 2D object you must change the rotation in Z axis.

You can use the above code with the Euler angles set to zero for X and Y. Here is an example

using UnityEngine;

public class Rotation_demo : MonoBehaviour
{
    Vector3 rot=new Vector3(0,0,1);
  
    void Update()
    {
       transform.Rotate(rot);
        
    }
}

Here is the output for the above code

Square Rotating around its own axis at 1 degree per frame.

Reset rotation using Quaternion.identity

What is Quaternion.identity?

Quaternion.identity refers to zero rotation in all axis. Quaternion identity is frequently used for instantiating an object with zero rotation in Unity.

Quaternion.identity is equal to setting a quaternion value of (0,0,0,1) to a game object.

Now let’s use it to reset a gameobject’s transform.

Every now and then during gameplay we tend to rotate the camera to an angle where it is no longer useful. At that time, we reset the camera view to start from the beginning.

Unity has an inbuild function to reset rotation. It’s a part of Quaternion. You just have to set the rotation to Quaternion.identity. This will reset the rotation to (0,0,0).

Here is a sample code.

using UnityEngine;

public class rotation_example : MonoBehaviour
{
   Vector3 rot=new Vector3(0,0,1);
  
    public void On_button_press()
    {
        transform.rotation=Quaternion.identity;
            
    }
}

You can assign the function to a UI button to reset the rotation when the player wants.

Video Tutorial

Hope this was helpful. If you have any other question regarding Rotation or Quaternion, leave them in the comment box below.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading