using UnityEngine;
using System.Collections;
public class PolarToGeographical : MonoBehaviour {
public Transform planet;
float planetRadius {
get {
return planet.gameObject.GetComponent<SphereCollider>().radius;
}
}
Vector3 relPos {
get {
return this.transform.position - planet.position;
}
}
struct Directionality {
public Vector3 up;
public Vector3 north;
public Vector3 east;
public Vector3 west {
get {
return east * -1f;
}
}
public Vector3 south {
get {
return north * -1f;
}
}
public Vector3 down {
get {
return up * -1f;
}
}
}
struct Geographical {
public float latitude;
public float longitude;
public float height;
}
//returns current directionality
Directionality getDirectionality() {
Directionality direction = new Directionality ();
direction.up = relPos.normalized * -1f;
direction.east = Vector3.Cross (Vector3.up, direction.up).normalized;
direction.north = Vector3.Cross (direction.up, direction.east).normalized;
return direction;
}
Geographical getGeographical() {
Geographical geo = new Geographical ();
//Use a more complicated solution for vMod if the planet will move or rotate.
//goal is to project onto planet's xz-plane
//I recommend this transform's worldToLocalMatrix method
//docs.unity3d.com/ScriptReference/Transform-worldToLocalMatrix.html
Vector3 vMod = relPos;
vMod.y = 0f;
geo.latitude = Vector3.Angle (vMod, relPos);
if (relPos.y < 0f)
geo.latitude *= -1f;
geo.longitude = Vector3.Angle (vMod, planet.forward);
if (relPos.x < 0f)
geo.longitude *= -1f;
geo.height = (relPos.magnitude - planetRadius) * -1f;
return geo;
}
void OnDrawGizmos() {
//unnecessary, but reads better
Vector3 pos = this.transform.position;
Directionality direction = getDirectionality ();
Gizmos.color = Color.green;
Gizmos.DrawLine (pos, pos + direction.up);
Gizmos.color = Color.red;
Gizmos.DrawLine (pos, pos + direction.east);
Gizmos.color = Color.blue;
Gizmos.DrawLine (pos, pos + direction.north);
Geographical geo = getGeographical ();
this.gameObject.name = (
"Lon: "
+ geo.longitude.ToString("N")
+ ", Lat: "
+ geo.latitude.ToString("N")
+ ". Ht: "
+ geo.height.ToString("N")
);
}
}