ゲームサウンド


ボリュームを上げて。赤い四角が障害物にぶつかったときに「ダンク」が聞こえますか?








サウンドを追加する方法は?

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