Witty remark!

github

Spherical Coordinates and Spherical Motion in Unity

Well since my last post I've refined the spherical movement behavior in the previous post's Unity demo. There is a lot of trigonometric math, so to make it easier I've included an interactive demo and a demo repository to go along with it.

What even is spherical coordinates?

We live in a Cartesian world where the coordinates are displayed on three different axises; X, Y and Z. In Unity (or any computer graphics program) we designate positions by using vectors consisting of these coordinates.

Spherical coordinate system is an alternative coordinate system, useful for describing points on a sphere (duh). In this coordinate system, very similar to the Cartesian coordinate system, there are three axises; "radius", "polar angle" and "elevation" (also known as azimuth). In Unity's case (a left-handed coordinates system) we can think polar and elevation coordinates as horizontal and vertical positions on the surface of a sphere.

spherical-motion.png

I am not going to go into details of the math and converting between these two coordinate systems as there are many good guides on how to do that (its also included in the repository at the bottom of this post) Instead I am going to show the demo.

Below the demo player you can use the sliders to adjust the target positions and where the "mover" will go. Use N and M buttons to apply force towards Cartesian and spherical targets respectively.

(Quick Note: There seems to be a bug when there is a difference of both elevation and polar on the spherical target, I'll fix it when I have more time.)

In the demo, the mover object essentially gets "spherical force" applied to it and moves towards the targeted position. The object simulates drag and acceleration just like a simple cartesian movement behavior would do. The reason there are two different targets is that one of the targets has a spherical coordinate and other has Cartesian coordinates. I've put two different coordinate system targets to show the smoothness of the movement between different coordinate systems.

Also note that I knowingly made the drag low and acceleration high to show a certain flaw on the spherical motion, which is circling. If an object is moving too fast and there is angle difference between the target and the mover position, there might be circling. In these cases it might be smart to increase the drag or lower the acceleration depending on the object's proximity to target.

Repository

Repository for the demo is here The meat of the project is in the "SphericalCoords" class. It implements a "Vector3" like interface to manipulate spherical coordinates and convert between the Cartesian and spherical coordinates. Note that I've only included the scripts to reduce the clutter. To implement the similar behavior I've done in the demo, just put both "SphericalMover" and "SphericalMotion" scripts on the same gameobject.