3D小遊戲(three)-分數顯示更新

_Zou發表於2020-12-19
  1. src/view3d/font.js匯入字型
  2. Src/view3d/ScoreText.js

import font from './font'

 

export default class Text {

constructor () {

 

}

 

init (options) {//初始化

this.material = new THREE.MeshBasicMaterial({ color: (options && options.fillStyle) ? options.fillStyle : 0xffffff, transparent: true })

if (options && options.opacity) this.material.opacity = options.opacity

this.options = options || {}

const geometry = new THREE.TextGeometry('0', { 'font': font, 'size': 6.0, 'height': 0.1 })

this.instance = new THREE.Mesh(geometry, this.material)

this.instance.name = 'scoreText'

}

updateScore (score) {//更新分數模型

const scoreStr = score.toString()

this.instance = new THREE.Mesh(new THREE.TextGeometry(scoreStr, { 'font': font, 'size': 6.0, 'height': 0.1 }), this.material)

}

}

  1. game-page.js

Init

this.score = 0

this.scoreText = new ScoreText()//分數初始化

this.scoreText.init({

fillStyle: 0x666699

})

this.render()

this.addScore()

JS中

addScore () {

this.scene.addScore(this.scoreText.instance)//載入文字

}

updateScore (score) {

this.scoreText.updateScore(score)

this.scene.updateScore(this.scoreText.instance)

}

checkBottleHit中

this.updateScore(++this.score)//更新分數

Restrat

this.updateScore(0)

  1. scene/scene.js

addScore (scoreInstance) {//載入文字

this.currentScore = scoreInstance

this.camera.instance.add(scoreInstance)

scoreInstance.position.x = -20

scoreInstance.position.y = 40

}

updateScore (scoreInstance) {//更新

this.camera.instance.remove(this.currentScore)

this.currentScore = scoreInstance

this.camera.instance.add(scoreInstance)

scoreInstance.position.x = -20

scoreInstance.position.y = 40

}

注:此時會有一BUG當再次重新開始是background會出現一個三角空白、視覺補救方法:

renderer.setClearColor(0xd7dbe6, 1.0)//與background一致

相關文章