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