更新于 

Solar System 模拟太阳系

星空、太阳与点光源

星空背景

使用一张星空背景图为天空盒的六面贴图

1
2
3
4
5
6
7
8
9
const cubeTextureLoader = new THREE.CubeTextureLoader()
scene.background = cubeTextureLoader.load([
stars,
stars,
stars,
stars,
stars,
stars,
])
太阳

太阳位于星系中心点位置

1
2
3
4
5
6
let sunGeometry = new THREE.SphereGeometry(16, 30, 30)
let sunMetarial = new THREE.MeshBasicMaterial({
map:textureLoader.load(sunTexture)
})
let sun = new THREE.Mesh(sunGeometry, sunMetarial)
scene.add(sun)
点光源

为太阳添加pointLight点光源,
可以对pointLight的一些属性进行初始化:

  • color 颜色
  • intensity 强度
  • distance 延伸距离
1
2
const pointLight = new THREE.PointLight(0xffffff, 2, 300)
sun.add(pointLight)

行星的自转与公转

行星

一共要创建九个行星(算上冥王星),方便起见我们需要写一个创建函数:

1
2
3
4
5
6
7
8
9
10
function createPlanet(radius,texture,position){
const geometry = new THREE.SphereGeometry(radius,30,30)
const metarial = new THREE.MeshStandardMaterial({
map:textureLoader.load(texture)
})
const mesh = new THREE.Mesh(geometry,metarial)
mesh.position.set(position,0,0)
scene.add(mesh)
return mesh
}

再为每个行星调用

1
2
3
4
5
6
7
8
9
const mercury = createPlanet(3.2, mercuryTexture,28)
const venus = createPlanet(4.2, venusTexture,44)
const earth = createPlanet(3, earthTexture,62)
const mars = createPlanet(2.8, marsTexture,78)
const jupiter = createPlanet(15, jupiterTexture,100)
const saturn = createPlanet(10, saturnTexture,138)
const uranus = createPlanet(7, uranusTexture,176)
const neptune = createPlanet(8, neptuneTexture,200)
const pluto = createPlanet(2.8, plutoTexture,216)
自转与公转

如果需要所有行星都围绕太阳转动,可以把所有行星都加在太阳的子类中,
这样当太阳自时,其它行星也都随之转动,
但是这样存在一个问题:
不同行星的公转速度不同。

因此需要给每个行星都配置一个幽灵恒星
假设这些恒星全都位于太阳位置,以不同速度自转:

1
2
3
4
5
6
7
function createPlanet(radius,texture,position,ring){
const obj = new THREE.Object3D()
// 创造行星mesh...
obj.add(mesh)
scene.add(obj)
return {obj:obj,mesh:mesh}
}

再在animate中进行公转和自转的操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function animate(){
sun.rotateY(0.004)
// 公转
mercury.obj.rotateY(0.004)
venus.obj.rotateY(0.002)
earth.obj.rotateY(0.02)
mars.obj.rotateY(0.018)
saturn.obj.rotateY(0.038)
jupiter.obj.rotateY(0.04)
uranus.obj.rotateY(0.03)
neptune.obj.rotateY(0.032)
pluto.obj.rotateY(0.008)
// 自转
mercury.mesh.rotateY(0.04)
venus.mesh.rotateY(0.015)
earth.mesh.rotateY(0.01)
mars.mesh.rotateY(0.008)
saturn.mesh.rotateY(0.0009)
jupiter.mesh.rotateY(0.002)
uranus.mesh.rotateY(0.0004)
neptune.mesh.rotateY(0.0001)
pluto.mesh.rotateY(0.00007)

renderer.render(scene , camera)
}

行星环

土星和天王星都有星环,
因此需要修改行星工厂函数,绘制星环