Suoni di gioco

Accendi il volume. Quando il quadrato rosso colpisce un ostacolo, senti il suono di impatto?






Come aggiungere suoni?

Usa l'elemento HTML5 <audio> per aggiungere suoni e musica al tuo gioco.

Nell'esempio seguente, creiamo un nuovo costruttore di oggetto per gestire l'oggetto sound:

istanza

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

Per creare un nuovo oggetto sound, utilizzare suono Costruttore, quando il quadrato rosso colpisce l'ostacolo, riproduce il suono:

istanza

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

Prova personalmente

Musica di sfondo

Per aggiungere la musica di sfondo al gioco, aggiungi un nuovo oggetto sound e inizia a riprodurre quando il gioco viene avviato:

istanza

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

Prova personalmente