Geomys Unity Tutorials

With all the time I’ve spent helping people on unityAnswers in the last month, I decided I should polish some of these up, add explanations and descriptions, and share them here. The first I’m going to share is a bit arcane: Polar coordinates, and converting between simplified polar coordinates – essentially latitude and longitude – and standard Cartesian vector coordinates. I got rather carried away helping someone with this problem, and just had fun playing with it.

The meat of this one is just two simple functions, PolarToCartesian and CartesianToPolar, which do the conversion from one to the other. The rest is just a test rig to visualize and test these functions. Centered in the view is a green reference sphere; piercing this is a red “arrow,” indicating the direction of a set of latitude/longitude values, and a yellow cube indicates the position of a point vector. Click and drag to rotate the view around the object. Text fields let you view and modify the components of point and the angles, with the arrow and box elements updating in-scene automatically. You can move the box by changing it’s x,y,z position, then click “Apply to Polar” to convert and auto-set latitude and longitude, causing the arrow to point to the box, or use the “Apply to point” button to reposition the box in the direction of the arrow.

[download Unity project]

The meat is two fairly simple functions, PolarToCartesian and CartesianToPolar. I’ll let their comments speak for themselves…

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;

    //do the atan thing to get our latitude
    polar.x = Mathf.Atan2(-point.y,xzLen);

    //convert to degrees
    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);
    //generate a rotation quat based on polar's angle values
    var rotation = Quaternion.Euler(polar.x,polar.y,0);
    //rotate origin by rotation
    var point:Vector3=rotation*origin;
    return point;

Never put code in here before, thinking I ought to look for a wp plugin that does syntax highlighting and the like, but this works for now. I’ll likely revisit this project later, polish this up and implement proper classes encapsulating full polar coordinate routines and conversion methods into Polar2 and Polar3 classes; got an idea I might play with later that would need something like this in a robust form. For now, this demo should help anyone else needing to do the same thing get started!


Did you like this? Share it:
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *