Skip to content

Instantly share code, notes, and snippets.

@EliCDavis
Created June 8, 2023 01:19
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 EliCDavis/cdfbcf0ebeb997b5486f5497993a38ab to your computer and use it in GitHub Desktop.
Save EliCDavis/cdfbcf0ebeb997b5486f5497993a38ab to your computer and use it in GitHub Desktop.
FibonacciSphere in Unity3D
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