mardi 5 mars 2019

Generate particles for spiral galaxy in THREE.js

I would like to create simple spiral galaxy using THREE.Points in THEE.js. I cannot figure out how to generate spiral arms. Is there any (not too difficult) way to do this?

Here I created fiddle. There is flattened sphere, but without spiral arms.

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight)
camera.position.z = 1500
scene.add(camera)
const renderer = new THREE.WebGLRenderer({ clearColor: 0x000000 })
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

// Random function with normal dustribution.
const normalRandom = (mean, std) => {
    let n = 0
    
    for (let i = 1; i <= 12; i++) {
      n += Math.random()
    }

    return (n - 6) * std + mean
}

const geometry = new THREE.Geometry()
const galaxySize = 1000

// Generate particles for spiral galaxy:
for (let i = 0; i < 10000; i++) {
  var theta = THREE.Math.randFloatSpread(360) 
  var phi = THREE.Math.randFloatSpread(360)
  const distance = THREE.Math.randFloatSpread(galaxySize)

  // Here I need generate spiral arms instead of sphere.
  geometry.vertices.push(new THREE.Vector3(
         distance * Math.sin(theta) * Math.cos(phi),
     distance * Math.sin(theta) * Math.sin(phi),
     distance * Math.cos(theta) / 10
  ))
}

const spiralGalaxy = new THREE.Points(geometry, new THREE.PointsMaterial({ color: 0xffffff }))
scene.add(spiralGalaxy)

function render() {
    requestAnimationFrame(render)
    renderer.render(scene, camera)
    spiralGalaxy.rotation.x += 0.01;
    spiralGalaxy.rotation.y += 0.01;
}

render()
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/102/three.min.js"></script>



Aucun commentaire:

Enregistrer un commentaire