Unity 3D – How to rotate an object around and also along with a specific point ?

While building one of the Holographic App demo for my  Holographic App Development Using Microsoft HoloLens  series, I was trying out rotating an objects around it different axis along with rotate around to an  orbit. This post just talk about how to achieve the rotation part for both of the cases in unity.

Consider you have a Cube object, and first of all you want to rotate it along with it’s own axis.

Add a new Script ( Called it as CubeScript) and add the following line of code inside the Update() Method.

this.transform.Rotate(new Vector3(Random.value, Random.value, Random.value));

Random.Value returns a random number between 0.0 and 1.0.  Attach the script with the Cube object

Once you run your Unity Scene, you will find the cube is rotating to its own axis. As we are setting the values as random, you will find the rotation is not happening in fixed direction.

Now, to rotate around , add the following line of code. Transform.RotateAround  transform about axis passing through the point in world coordinates.

this.transform.RotateAround(Vector3.zero, Vector3.up, 1.0f);

Here is how the overall scripts looks like

using UnityEngine;
using System.Collections;

public class CubeRotateScript : MonoBehaviour
{

// Use this for initialization
void Start()
{

}

// Update is called once per frame
void Update()
{
this.transform.Rotate(new Vector3(Random.value, Random.value, Random.value));
this.transform.RotateAround(Vector3.zero, Vector3.up, 1.0f);
}
}

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.