Ultimele tutoriale de dezvoltare web
 

HTML Joc de sunet


Da volumul mai tare. Ai auzit un "dunk" atunci când pătrat roșu lovește un obstacol?








Cum se adaugă sunete?

Utilizați HTML5 <audio> Elementul pentru a adăuga sunet și muzică la jocurile tale.

În exemplele noastre, vom crea un nou constructor obiect de a manipula obiecte de sunet:

Exemplu

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

Pentru a crea un nou obiect de sunet utiliza sound constructor, iar atunci când pătrat roșu lovește un obstacol, reda sunetul:

Exemplu

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

...

}
Încearcă - l singur »

Muzica de fundal

Pentru a adăuga muzică de fundal la joc, adăugați un nou obiect de sunet, și începe să joci atunci când începe jocul:

Exemplu

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();
}
Încearcă - l singur »