Skip to content

Instantly share code, notes, and snippets.

@roboshoes
Last active November 22, 2017 22:29
Show Gist options
  • Save roboshoes/b2167332adf5878f37d442fa29d31ac5 to your computer and use it in GitHub Desktop.
Save roboshoes/b2167332adf5878f37d442fa29d31ac5 to your computer and use it in GitHub Desktop.
Implementation of spherical coordinates in C# (based on https://github.com/mrdoob/three.js/blob/master/src/math/Spherical.js)
using UnityEngine;
public struct Spherical {
public float Radius;
public float Phi;
public float Theta;
Spherical( float radius = 1f, float phi = 0f, float theta = 0f ) {
Radius = radius;
Phi = phi;
Theta = theta;
}
public Spherical SetFromVector3( Vector3 vector ) {
Radius = vector.magnitude;
if ( Radius == 0f ) {
Theta = 0f;
Phi = 0f;
} else {
Theta = Mathf.Atan2( vector.x, vector.z );
Phi = Mathf.Acos( Mathf.Clamp( vector.y / Radius, - 1, 1 ) );
}
return this;
}
public Vector3 SetVector3( ref Vector3 target ) {
var sinPhiRadius = Mathf.Sin( Phi ) * Radius;
target.x = sinPhiRadius * Mathf.Sin( Theta );
target.y = Mathf.Cos( Phi ) * Radius;
target.z = sinPhiRadius * Mathf.Cos( Theta );
return target;
}
public static Spherical FromVector3( Vector3 vector ) {
return new Spherical().SetFromVector3( vector );
}
}
@roboshoes
Copy link
Author

Obviously all credit goes to bhouston and WestLangley for writing the THREE.js implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment