2 Mins Read  February 28, 2014  Cuelogic Insights

How to rotate object in unity3d using Quaternion

Following tutorial will guide you how to rotate an object using Quaternion.

  1. I assume you might be aware of basics about unity.
  2. There are different ways for rotating object’s, For example :: rotation using rigidbody, rotation using Quaternion etc .
  3. Choosing the technique for rotating an object depends on the type of object, By “ Type of object ” i mean weather the object has a rigidbody component, character controller or nothing attached to it.
  4. Following technique of rotation is best suited only for  those object which do not have any of the above component.
  5. If  you are using rigidbody component on object then refer following
    link :: How to rotate object in unity3d using Rigidbody
  6. Create a sample  project and add a plane to the scene along with  a cube(TargetObject)  towards which we have rotate our rotationObject(player just to differentiate between two objects).
  7. Now we will add rotation script to object. (QuaternionRotation.cs) using UnityEngine; using System.Collections; public class QuaternionRotation : MonoBehaviour { float rotationSpeed=0.5f ;// This Must be less than 1 and greater than 0 GameObject targetObject=null; // Use this for initialization void Start () { // get target object tobe rotated at targetObject=GameObject.FindGameObjectWithTag(“TargetObject”) as GameObject; } // Update is called once per frame void Update () { if(targetObject==null){ Debug.Log(“[ERROR] => Traget object is null , Can’t Rotate”); return; } // get position of target object Vector3 targetPosition=targetObject.transform.position; // calculate rotation to be done Quaternion targetRotation = Quaternion.LookRotation(targetPosition – transform.position); //NOTE :: If you don’t want rotation along any axis you can set it to zero is as :- // Setting Rotation along z axis to zero targetRotation.z=0; // Setting Rotation along x axis to zero targetRotation.x=0; // Apply rotation transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime); } }
  8. Now run the scene , And you can see Player object rotating to target object.

Note :-

  1. If you have added rigidybody to rotationObject (player) then you must rotate object using physics (Force,Torque).
  2. Rotation using Quaternion must only be used on object which do not have rigidbody.

Recommended Content

Go Back to Main Page