DAY 19
2
Modern Web

## 用 Three.js 來當個創世神 (18)：專案實作#9 - 爆炸特效

Photo by Cristian Escobar on Unsplash

## 觀察預期效果

1. 在第一個瞬間苦力怕會直接消失
2. 緊接著是好幾個一團一團的爆炸
3. 每一團有不同顏色
4. 每一團爆炸間有間隔的出現

## 專案實作

### 1. 爆炸物件設定

``````// points
const pointCount = 1000
const movementSpeed = 10
let explosion = [] // 爆炸物件陣列
let size = 10

class Explosion {
constructor(x, y, z, color) {
...
this.material = new THREE.PointsMaterial({
size: size,
color: color,
map: smokeTexture,
blending: THREE.CustomBlending,
depthWrite: false,
transparent: true,
opacity: 0.7
})
...
}
...
}
``````

``````THREE.NoBlending
THREE.NormalBlending
THREE.SubtractiveBlending
THREE.MultiplyBlending
THREE.CustomBlending
``````

### 2. 用 dat.GUI 設定爆炸開關與重置

``````this.explosionTrigger = function() {
for (let i = 0; i < scene.children.length; i++) {
const object = scene.children[i]

// 場景內有苦力怕才爆炸
if (object.name === 'creeper') {
// 清除之前爆炸粒子
if (explosion) {
const len = explosion.length
if (len > 0) {
for (let i = 0; i < len; i++) {
explosion[i].destroy()
}
}
explosion.length = 0
}

// 移除苦力怕
scene.remove(creeperObj.creeper)

// 產生爆炸
explosion[0] = new Explosion(0, 0, 0, 0x000000)
explosion[1] = new Explosion(5, 5, 5, 0x333333)
explosion[2] = new Explosion(-5, 5, 10, 0x666666)
explosion[3] = new Explosion(-5, 5, 5, 0x999999)
explosion[4] = new Explosion(5, 5, -5, 0xcccccc)
}
}
}
``````

``````this.resetCreeper = function() {
}
``````

### 3. 爆炸動畫設定

``````function render() {
if (explosion) {
const len = explosion.length
if (len > 0) {
for (let i = 0; i < len; i++) {
explosion[i].update()
}
}
}
...
requestAnimationFrame(render)
renderer.render(scene, camera)
}
``````

### 4. 調整相機設定

``````// 相機設定
camera = new THREE.PerspectiveCamera(
60,
window.innerWidth / window.innerHeight,
20,
1000
)
camera.position.set(50, 50, 50)
camera.lookAt(scene.position)
``````