I'm writing a homework assignment for a JS class, and the teacher wants us to have a weapon sound when firing, but stop making sound when out of ammo. I have the sound effect working for when the gun fires, but it continues making the sound when clicked with 0 ammo.
I tried doing an else{} function, but this breaks the "ammo display" in my browser, and the sound would continue playing anyway.
HTML:
<input type="button" value="Heal" class="shoot" onclick="shoot();">
<audio id="heal" src="sound/heal.mp3">
JS: Displays ammo starting at a maximum of 6 shots, with 6 shots in reserve, and counts down each time it is fired.
function shoot() {
if (currentAmmo > 0) {
currentAmmo--;
}
var shoot = document.getElementById("shoot");
shoot.play();
updatescreen();
function updatescreen() {
document.getElementById("total-ammo").innerHTML = "Bullets in Gun:</br>" + totalAmmo;
document.getElementById("current-ammo").innerHTML = "Reload Ammo:</br>" + currentAmmo;
}
You just need to move the play command inside the if-condition.
if (currentAmmo > 0) {
currentAmmo--;
var shoot = document.getElementById("shoot");
shoot.play();
}
updatescreen();