Skip to content

Instantly share code, notes, and snippets.

@JustinFincher
Created March 3, 2016 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinFincher/5381bc9ddec1605fb7a8 to your computer and use it in GitHub Desktop.
Save JustinFincher/5381bc9ddec1605fb7a8 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class JZ_PlanetHelper : MonoBehaviour
{
// return x -180.0 ~ 180.0
// return y -90.0 ~ 90.0
public static Vector2 CartesianToPolarDegress(Vector3 point)
{
var polar = Vector2.zero;
//calc longitude
polar.x = Mathf.Atan2(point.x,point.z);
//this is easier to write and read than sqrt(pow(x,2), pow(y,2))!
var xzLen = new Vector2(point.x,point.z).magnitude;
//atan2 does the magic
polar.y = - Mathf.Atan2(-point.y,xzLen);
//convert to deg
polar *= Mathf.Rad2Deg;
return polar;
}
// return x 0.0 ~ 1.0
// return y 0.0 ~ 1.0
public static Vector2 CartesianToPolarUV(Vector3 point)
{
var polar = Vector2.zero;
//calc longitude
polar.x = Mathf.Atan2(point.x,point.z);
//this is easier to write and read than sqrt(pow(x,2), pow(y,2))!
var xzLen = new Vector2(point.x,point.z).magnitude;
//atan2 does the magic
polar.y = - Mathf.Atan2(-point.y,xzLen);
//convert to deg
polar *= Mathf.Rad2Deg;
polar.y = (polar.y + 90.0f)/180.0f;
polar.x = 1.0f-(polar.x +180.0f)/360.0f;
return polar;
}
public static Vector3 PolarUVToCartesian(Vector2 polar)
{
//an origin vector, representing lat,lon of 0,0.
polar.x = (1.0f - polar.x)*360.0f - 180.0f;
polar.y = polar.y*180.0f - 90.0f;
var origin= new Vector3(0,0,1);
//build a quaternion using euler angles for lat,lon
var rotation = Quaternion.Euler( - polar.y,polar.x,0);
//transform our reference vector by the rotation. Easy-peasy!
Vector3 point =rotation*origin;
//Debug.Log("PolarDegreesToCartesian(Vector3 point)" + point.x + " " + point.y + " " + point.z);
return point;
}
public static Vector3 PolarDegreesToCartesian(Vector2 polar)
{
//an origin vector, representing lat,lon of 0,0.
var origin= new Vector3(0,0,1);
//build a quaternion using euler angles for lat,lon
var rotation = Quaternion.Euler( - polar.y,polar.x,0);
//transform our reference vector by the rotation. Easy-peasy!
Vector3 point =rotation*origin;
//Debug.Log("PolarDegreesToCartesian(Vector3 point)" + point.x + " " + point.y + " " + point.z);
return point;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment