如何在每次击中对象时在画布上添加随机音频



我是编程新手。我试着用画布做一个蛇的游戏。我想在每次遇到障碍时添加一个随机音频。当我添加一个音频时,它完全可以工作,但我不能用两个音频做同样的事情。我试着使用数组等,但没有成功。我该怎么做?

JAVASCRIPT

const canvas = document.getElementById('oyun');
const ctx = canvas.getContext('2d');
let speed = 7;
let tileCount = 24;
let tileSize = canvas.width / tileCount - 2;
let headX = 12;
let headY = 12;
let appleX = 5;
let appleY = 5;
let audio = document.getElementById("sesefekt");
let xVelocity = 0;
let yVelocity = 0;
function drawGame(){
changeSnakePosition();
checkAppleCollision();
clearScreen();
drawApple();
drawSnake(); 
setTimeout(drawGame, 1000 / speed);
}
function clearScreen(){
ctx.fillStyle = '#a40af7';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function drawSnake() {
ctx.fillStyle = 'purple';
ctx.fillRect(headX * tileCount, headY * tileCount, tileSize,tileSize);
}
function changeSnakePosition() {
headX = headX + xVelocity;
headY = headY + yVelocity;
}
function drawApple() {
ctx.fillStyle = "plum";
ctx.fillRect(appleX * tileCount, appleY * tileCount, tileSize, tileSize);
}
function checkAppleCollision() {
if(appleX == headX && appleY == headY){
appleX = Math.floor(Math.random() * tileCount);
appleY = Math.floor(Math.random() * tileCount);
audio.play();  
}
}
//hareket etme fonksiyonları
document.body.addEventListener('keydown', keyDown);
function keyDown(event) {
//yukarı
if (event.keyCode == 38){
if(yVelocity == 1)
return;
yVelocity = -1;
xVelocity = 0;
}
//aşağı
if (event.keyCode == 40){
if(yVelocity == -1)
return;
yVelocity = 1;
xVelocity = 0;
}
//sağ
if (event.keyCode == 39){
if(xVelocity == -1)
return;
yVelocity = 0;
xVelocity = 1;
}
//sol
if (event.keyCode == 37){
if(xVelocity == +1)
return;
yVelocity = 0;
xVelocity = -1;
}
}
drawGame();

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SNAKE YILANNNNNN</title>
<style>
body{
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: black;   
}
canvas{
box-shadow: darkmagenta 20px 10px 50px;
}
</style>
</head>
<body>
<audio id="sesefekt">
<source src="bruh.mp3" type="audio/mp3">
<source src="a.mp3" type="audio/mp3">
</audio>
<h1 style="color: blueviolet; text-shadow: lightblue 20px 10px 50px;">YILAN OYUNU AMA BİR DEĞİŞİK</h1>
<canvas id="oyun" width="576" height="576"></canvas>

<script src="index.js"></script>
</body>
</html>

现在,每次发生碰撞时,您基本上都在玩游戏。如果音效已经在播放,你就不能再开始了。有几种方法可以解决这个问题,我可以想到:

  1. 在需要播放声音效果时创建一个新元素,并在效果完成后立即将其删除
  2. 使用像下面这样的API/框架参考示例

最新更新