I am trying to create an amateur mmorpg JavaScript browser game, multiplayer actually. This is a mmorpg so I am going to generate enemies randomly (doesn't matter now), the point is I have made a constructor function which creates a separate object, not linked to the prototype (which is nice). This separate object will be some individual npc, the amount will depend on how many we generate.
function myEnemy(posX,posY) {
this.uuid = 'aa1b05',
this.health = 2000,
this.shield = 2000,
this.posX = posX,
this.posY = posY,
this.speed = 320,
this.damage = 80,
this.ratio = 1000,
//this.target = 'uuid',
this.aggro = true,
this.strike = function() {
this.health -= this.damage
console.log(this.health)
//if(this.aggro === true) { setTimeout(this.strike(), this.ratio); }
}
this.attack = function() {
if(this.aggro === true) { setTimeout(this.strike(), this.ratio); }
}
};
Don't bother about the uuid
, it's work in progress.
The enemy does have some basic stats, health, position, speed, etc. I have removed some methods from this example for simplicity.
This code here spawns an enemy:
let enemy = new myEnemy(0,0)
In this example I am just reducing the enemy's health each time it strikes, because I haven't implemented the targeting system yet. It's working fine, the problem comes once this.attack() is executed it's it only strikes once.
The other problem is the reason why I commented that line in this.strike()
, instead of repeating the action each second it repeats the action so fast that it crashes my computer.
As far as I have gone, no matter what I try, setTimeout
doesn't work.
My goal is to have the enemy do the strike function while aggro is = true, I have also tried do while loops without any success, the problem is setTimeout
.
Update
This is not a duplicate, I have also tried to remove the ()
from the strike function without success, it attacks once and then returns NaN
, stopping the loop.