在THREE.js中为螺旋星系生成粒子

问题描述 投票:2回答:1

我想在THREE.js中使用THREE.Points创建一个简单的螺旋星系。 我无法弄清楚如何生成旋臂。有没有(不太难)这样做?

在这里,我创建了这个fiddle。有一个扁平的球体,但没有旋臂。

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 to generate spiral arms instead of a 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>
javascript math random three.js spiral
1个回答
5
投票

看起来你已经用极坐标系自己做了很多繁重的工作。但请记住,角度是以弧度而不是以度为单位,所以不应使用360,而应使用PI * 2。现在你所要做的就是同时增加distancetheta以创建一个螺旋,而phi保持接近0以创建星系的黄道面。

  • distance将从0成长为galaxySize
  • theta将从0增长到Math.PI(或PI * 2,如果你想要更紧的螺旋)
  • phi接近0
// Temp variables to assign new values inside loop
var norm, theta, phi, thetaVar, distance;

// Generate particles for spiral galaxy:
for (let i = 0; i < 1000; i++) {
    // Norm increments from 0 to 1
    norm = i / 1000;

    // Random variation to theta [-0.5, 0.5]
    thetaVar = THREE.Math.randFloatSpread(0.5);

    // Theta grows from 0 to Math.PI (+ random variation)
    theta = norm * Math.PI + thetaVar;

    // Phi stays close to 0 to create galaxy ecliptic plane
    phi = THREE.Math.randFloatSpread(0.1);

    // Distance grows from 0 to galaxySize
    distance = norm * 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,而是将phi的范围限制为[-0.1, 0.1]。你可以在行动中看到它in this fiddle

© www.soinside.com 2019 - 2024. All rights reserved.