Skip to content

Instantly share code, notes, and snippets.

@NullDev
Created April 16, 2022 19:27
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 NullDev/b83d4ea264ce86598a715427b2b2c31c to your computer and use it in GitHub Desktop.
Save NullDev/b83d4ea264ce86598a715427b2b2c31c to your computer and use it in GitHub Desktop.
Fibonacci Sphere in Three.js
import { OrbitControls } from "https://cdn.jsdelivr.net/npm/three@0.121.1/examples/jsm/controls/OrbitControls.js";
// DEMO: https://jsfiddle.net/NullDev/8bjt60p9/
const numberOfPoints = 1500;
const radiusOfSphere = 30;
const getFibonacciSpherePoints = function(samples = 1, radius = 1){
const points = []
const offset = 2 / samples
const increment = Math.PI * (3 - Math.sqrt(5));
for (let i = 0; i < samples; i++) {
let y = ((i * offset) - 1) + (offset / 2);
let distance = Math.sqrt(1 - Math.pow(y, 2));
let phi = ((i + 1) % samples) * increment;
let x = Math.cos(phi) * distance;
let z = Math.sin(phi) * distance;
x *= radius;
y *= radius;
z *= radius;
points.push({ x, y, z });
}
return points;
};
const initSceneAndAddFibonacciSphere = function(fibonacciSpherePoints){
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0xffffff, 70, 135);
scene.background = new THREE.Color(0xffffff);
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 500);
camera.position.set(0, 0, 100);
camera.lookAt(new THREE.Vector3(0, 0, 0));
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.screenSpacePanning = true;
controls.target.set( 0.0, 1.0, 0.0 );
controls.update();
for (let i = 0; i < fibonacciSpherePoints.length; i++){
const point = fibonacciSpherePoints[i];
const geometry = new THREE.SphereGeometry(0.2);
const material = new THREE.MeshBasicMaterial({ color: 0x59673C });
const sphere = new THREE.Mesh(geometry, material);
sphere.position.x = point.x;
sphere.position.y = point.y;
sphere.position.z = point.z;
scene.add(sphere);
}
renderer.render(scene, camera);
function animate(){
requestAnimationFrame(animate);
renderer.render(scene, camera);
controls.update();
}
animate();
};
initSceneAndAddFibonacciSphere(getFibonacciSpherePoints(numberOfPoints, radiusOfSphere));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment