Search code examples
javascripttimedelaytimedelay

(Game Programming) How to add delay between attacks?


I'm making a game where you control your character with the arrow keys and attack with 'A'. My problem is that the attack has no delay so when I hold 'A' the enemy's hp depletes rapidly. How do I add delay? I tried adding delay, here is my code:

var DELAY = 2;
var cooldown = 0;

function update(time) {

// UP
if (38 in keysDown) { 
    player.y -= player.speed * time;
}
// DOWN
if (40 in keysDown) { 
    player.y += player.speed * time;
}
// LEFT
if (37 in keysDown) {
    player.x -= player.speed * time;
}
// RIGHT
if (39 in keysDown) { 
    player.x += player.speed * time;
}

// 'A'
if(65 in keysDown) {
    player.attacking = true;
    cooldown -= time;
}
else
    player.attacking = false;

// Collision
if( (player.x + pImage.width-5) >= monster.x && 
    (player.x + pImage.width-5) < monster.x + enImage.width &&
    player.y >= monster.y && player.y < (monster.y + enImage.height) &&
    player.attacking) 
    {
        if(cooldown <= 0) {
            monster.hp -= player.dmg;
            cooldown = DELAY;
        }

        if(monster.hp <= 0) {
            relocEn();
        }
    }

}

The problem is that the cooldown counts only when I'm holding 'A' and resets only when the player is touching the monster. I want something like when I press 'A' the cooldown timer sets off. Also, I want the sprite(in attacking state) to go along with the delay and goes back to "standing" state. Thanks in advance


Solution

  • Here's what I would do:

    I would create a variable for the time of the last attack and move all your code relevant to attacking to another function. I'm assuming time is measured in milliseconds so you're probably going to want your delay to be in the hundreds.

    var DELAY = 400; //Change this to a higher value if it's not long enough.
    var timeSinceLastAttack = -400; // The opposite of the DELAY if you want to attack at the start. 
    
    function update(time) {
    
    ...
    
    // 'A'
    if(65 in keysDown 
        && time > (timeSinceLastAttack + DELAY) ) {
        player.attack();
        timeSinceLastAttack = time;
    } 
    

    Then in your attack() function you can do your collision detection.