게임 소리
소리를 크게 해 주세요. 빨간 박스가 장애물에 부딪혔을 때, 충돌 소리를 들었나요?
소리를 추가하는 방법?
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(); } }
새로운 소리 객체를 생성하려면 다음을 사용하십시오: 소리
빨간 사각형이 장애물과 충돌할 때, 소리를 재생하는 구조 함수입니다:
实例
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(); }