Having some fun with Rotations…

Before I get started on my main project, I decided to have a little fun and write a rotation class. This’ll come in handy for many projects down the line. Besides planets and orbiting objects, it can be used for power-up effects, insects, some jerk doing donuts on a lawn, and whatever else you want to have this behavior.

To start, I created the object I wanted to the others to orbit around. For the example I made a sphere and then gave it an Earth material. Then I created a simple class called ‘Rotate’ that I attached to the main object so it’ll… rotate.

I originally had just a float with the rotation speed. Then I thought it should be a Vector3 so I can make it rotate on more than one axis, and adjust it in the inspector. Besides, the Earth doesn’t rotate perfectly on the Y axis, it’s got a tilt.

So, I attached the Rotate class to my Earth game object and Behold! It rotates in whatever direction and speed I want.

Next, I created several smaller spheres as child objects of the Earth. To keep with the theme I gave them planet materials, too. Then I added the Rotate class to each one.

Since the parent object was rotating, all the child objects would rotate along with it unless I give them their own local rotations.

That’s where the Orbit class comes in.

The code in Start is just to randomize the orbit vectors and speed. I added a bool to enable the random values. Otherwise I can set each one manually.

In Update, I used transform.RotateAround and passed in a Transform as the pivot. As you might’ve guessed, I assigned the Earth object as the pivot. Then, for the direction of the orbit, I passed in the _orbitVector value, and then the speed multiplied by Time.deltaTime.

The end result is either carefully set orbits around the parent object, or….

ABSOLUTE CHAOS!!! 😅