Sonido de juego
- Página anterior Imágenes de juego
- Página siguiente Gravedad de juego
Aumente el volumen. ¿Escucha el sonido de impacto cuando el cuadrado rojo choca con un obstáculo?
Abajo
¿Cómo agregar sonido? Utilice el elemento HTML5 <audio> para agregar sonido y música a su juego.
En el siguiente ejemplo, creamos una nueva función constructora para manejar el objeto de sonido:
实例
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(); } }
Para crear un nuevo objeto de sonido, utilice Sonido
Constructor de función, cuando el cuadrado rojo choca con un obstáculo, se reproduce el sonido:
实例
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; } } ... }
Música de fondo
Para agregar música de fondo al juego, agregue un nuevo objeto sound y comience a reproducirlo al iniciar el juego:
实例
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(); }
- Página anterior Imágenes de juego
- Página siguiente Gravedad de juego