游戲聲音
請把聲音調大。當紅色方塊碰到障礙物時,您是否聽到撞擊聲?
如何添加聲音?
請使用 HTML5 <audio> 元素向您的游戲添加聲音和音樂。
在下面的例子中,我們創建一個新的對象構造函數來處理聲音對象:
實例
function sound(src) { this.sound = document.createElement("audio"); this.sound.src = src; this.sound.setAttribute("preload", "auto"); this.sound.setAttribute("controls", "none"); this.sound.style.display = "none"; document.body.appendChild(this.sound); this.play = function(){ this.sound.play(); } this.stop = function(){ this.sound.pause(); } }
如需創建一個新的聲音對象,請使用 sound
構造函數,當紅色方塊碰到障礙物時,播放聲音:
實例
var myGamePiece; var myObstacles = []; var mySound; function startGame() { myGamePiece = new component(30, 30, "red", 10, 120); mySound = new sound("bounce.mp3"); myGameArea.start(); } function updateGameArea() { var x, height, gap, minHeight, maxHeight, minGap, maxGap; for (i = 0; i < myObstacles.length; i += 1) { if (myGamePiece.crashWith(myObstacles[i])) { mySound.play(); myGameArea.stop(); return; } } ... }
背景音樂
要將背景音樂添加到游戲中,請添加新的 sound 對象,并在啟動游戲時開始播放:
實例
var myGamePiece; var myObstacles = []; var mySound; var myMusic; function startGame() { myGamePiece = new component(30, 30, "red", 10, 120); mySound = new sound("bounce.mp3"); myMusic = new sound("gametheme.mp3"); myMusic.play(); myGameArea.start(); }