Unity 3D Game Engine – Orbit Around an Object

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.