Shawn
Shawn

Reputation: 1183

javascript: my sound only plays once?

I made a skill for my game called Blitz. Its functionality is that you strike your opponent 3 times within 6 seconds.

I added sound files to the skill so you can have hearing cues on what you did so you don't necessarily have to read a text log. The problem i'm having though is when I hit my opponent 2 or more times, the sound file only plays once, not twice.

For example: This works - Hit, Miss, Hit. For example: This does not work - Hit, Hit (no sound), Miss (sound)

Why is it skipping or not playing?

// BLITZ SKILL 

document.getElementById("blitz").addEventListener('click', function() {
    atbReset();
    DB();
    RET();
    window.setTimeout(function() { blitzskill() }, 1000);
    window.setTimeout(function() { blitzskill() }, 2000);
    window.setTimeout(function() { blitzskill() }, 3000);
});

function blitzskill(){
    var criticalRoll = Math.floor(Math.random() * 100 + 1);
    var precisionRoll = Math.floor(Math.random() * cs.precision + 1);
    var npcParryRoll = Math.floor(Math.random() * ds.parry + 1);
    var damage = Math.floor(Math.random() * cs.strength * 1);

        if (character.energy <= 4) {
            addMessage("Not enough energy!")    
            return;
            }
        if (precisionRoll < npcParryRoll) {
            addMessage("The Dragon evaded your attack!");
            character.energy -= 5;
            miss.play(); // PLAY MISS SOUND
            }
        else if (damage - ds.armor <= 0) {
            character.energy -= 5;
            addMessage("Your opponents armor withstood your attack!");
            armor.play(); // PLAY MISS/ARMOR SOUND
            }   
        else if (cs.critical >= criticalRoll) {
            damage *= 2;
            damage -= ds.armor;
            dragon.hp -= damage;
            character.energy -= 5;
            document.getElementById("npchp").innerHTML = dragon.hp;
            addMessage("Critical Strike! Dragon suffers " + damage + " hp!")
            swoosh.play(); // PLAY HIT SOUND
            }   
        else {  
            dragon.hp -= damage;
            damage -= ds.armor;
            document.getElementById("npchp").innerHTML = dragon.hp;
            addMessage("You hit the dragon for " + damage + " hp!");
            character.energy -= 5;
            swoosh.play(); // PLAY HIT SOUND
            }
            document.getElementById("energy").innerHTML = character.energy;
};

Upvotes: 1

Views: 217

Answers (1)

megawac
megawac

Reputation: 11373

Try this:

swoosh.pause();// ensure sound is not already playing 
swoosh.currentTime = 0; //reset time
swoosh.play(); // PLAY HIT SOUND

All I'm doing is adding logic to ensure you call play at the sound start

Upvotes: 1

Related Questions