게임 사운드


볼륨을 올려줘. 빨간색 사각형이 장애물에 부딪힐 때 "덩크" 소리가 납니까?








소리를 추가하는 방법?

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;
    }
  }

...

}

배경 음악

게임에 배경 음악을 추가하려면 새 사운드 개체를 추가하고 게임을 시작할 때 재생을 시작합니다.

예시

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();
}