How to rotate object in unity3d using Rigidbody

Following tutorial will guide you how to rotate an object using rigidbody.I assume you might be aware of basics about unity.There are different ways for rotating object’s, For example :: rotation using rigidbody, rotation using Quaternion etc .

  1. 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 it it.
  2. Following technique of rotation is best suited only for  those object which have rigidbody component attached to it.
  3. If  your object is not using any component for Movement and Rotation then refer following link
     How to rotate object in unity using Quaternion
  4. 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).
  5. Now check “isTrigger” option of rotation object(player) and add rigidbody component to it. You can also lock rotation along any axis in “Inspector”.
using UnityEngine;
using System.Collections;

public class RigidbodyRotation : 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 to be rotated at
targetObject=GameObject.FindGameObjectWithTag("TargetObject") as GameObject;
}
// Update is called once per frame
void Update () {

}

void FixedUpdate () {
if(targetObject==null){
Debug.Log("[ERROR] => Traget object is null , Can't Rotate");
return;
}
// get position of target object
Vector3 targetPosition=targetObject.transform.position; 

// gives us vector to direction of target
Vector3 inverseVect=transform.InverseTransformPoint(targetPosition); 

// calculate angle by which you have to rotate
// Note -: This angle is calculated every Frame of FixedUpdate
float rotationAngle=Mathf.Atan2(inverseVect.x,inverseVect.z)*Mathf.Rad2Deg; 

// Now calculate  rotationVelocity to be applied every frame
Vector3 rotationVelocity=(Vector3.up*rotationAngle)*rotationSpeed*Time.deltaTime; 

// Calaculate his delta velocity   i.e required - current 
Vector3 deltavel=(rotationVelocity-rigidbody.angularVelocity); 

// Apply the force to rotate
rigidbody.AddTorque(deltavel,ForceMode.Impulse);
}
}
  • Now run the scene , And you can see Player object rotating to target object.
  • Note :: Also look for different types of forces to get variations.