Created
June 8, 2023 01:19
-
-
Save EliCDavis/cdfbcf0ebeb997b5486f5497993a38ab to your computer and use it in GitHub Desktop.
FibonacciSphere in Unity3D
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
public static class Fibonacci | |
{ | |
private static Dictionary<int, Vector3[]> fibonacciSphereCache = new Dictionary<int, Vector3[]>(); | |
public static Vector3[] FibonacciSphere(int samples) | |
{ | |
if (fibonacciSphereCache.ContainsKey(samples)) | |
{ | |
return fibonacciSphereCache[samples]; | |
} | |
var points = new Vector3[samples]; | |
var phi = Mathf.PI * (3.0f - Mathf.Sqrt(5.0f)); // golden angle in radians | |
for (int i = 0; i < samples; i++) | |
{ | |
var y = 1 - (i / (float)(samples - 1)) * 2; // y goes from 1 to -1 | |
var radius = Mathf.Sqrt(1 - y * y); // radius at y | |
var theta = phi * i; // golden angle increment | |
var x = Mathf.Cos(theta) * radius; | |
var z = Mathf.Sin(theta) * radius; | |
points[i] = new Vector3(x, y, z); | |
} | |
fibonacciSphereCache[samples] = points; | |
return points; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment