Unity3D Tip: Polar and Cartesian Coordinates in C#

Published Aug 04, 2015Last updated Feb 13, 2017
Unity3D Tip: Polar and Cartesian Coordinates in C#

While working on a game experiment called Alien Shootout with Unity3D, I wanted to have the main character rotate around the planet (like Super Mario Galaxy).

Here is how I did this:

function CartesianToPolar(point:Vector3):Vector2
     var polar:Vector2;
     //calc longitude
     polar.y = Mathf.Atan2(point.x,point.z);
     //this is easier to write and read than sqrt(pow(x,2), pow(y,2))!
     var xzLen = Vector2(point.x,point.z).magnitude; 
     //atan2 does the magic
     polar.x = Mathf.Atan2(-point.y,xzLen);
     //convert to deg
     polar *= Mathf.Rad2Deg;
     return polar;

 function PolarToCartesian(polar:Vector2):Vector3
     //an origin vector, representing lat,lon of 0,0. 
     var origin=Vector3(0,0,1);
     //build a quaternion using euler angles for lat,lon
     var rotation = Quaternion.Euler(polar.x,polar.y,0);
     //transform our reference vector by the rotation. Easy-peasy!
     var point:Vector3=rotation*origin;
     return point;

I have two functions to convert polar coordinates to cartesian ones and viceversa.

I also create a script called CustomGravity with the following public properties: latitude, longitude and height.

The CustomGravity script continuosly assigns the newly calculated polar position to the transform keeping in mind the values of the properties. I then add the CustomGravity script to every object that need to have a Super Mario Galaxy style.

I hope this is useful. Ask if you have questions 😉

Discover and read more posts from Carlotta Tatti
get started
Enjoy this post?

Leave a like and comment for Carlotta

Be the first to share your opinion

Get curated posts in your inbox

Read more posts to become a better developer