I'm using plain JavaScript and I've bee coding a hardcore platformer game. I want there to be multiple enemies at once and before I write up the code I have a question. How do i approach that? Do I just have to draw and give function to the enemies each time or is there a easier way?
1 Answer
This is a very hard question to answer since there are many things which come into account when you have to deal with these things.
What I usually do, is that I set up an array for all my enemies. Each enemy is basically an object with values such as their coordinates, direction, sprites etc., and what's most important, a draw() and an update() function.
In my main game loop, I usually have two cycles. One for updating the behavior of the enemies based on the player's location for example, and the other to actually draw them onto the canvas.
//A simple enemy object
function simpleEnemy(){
this.x;
this.y;
this.sprite;
this.update=function(){
//Any logic which decides where the enemy will be in the next frame
//This, in the end, just updates the X and Y coordinates of this entity
}
this.draw=function(){
ctx=gameArea.context;
ctx.drawImage(this.sprite,this.x,this.y);
}
}
//The main game loop
function updateArea(){
gameArea.clear();
//Any update and drawing function you have also comes here
for(i=0;i<enemies.length;i++){
enemies[i].update();
}
for(i=0;i<enemies.length;i++){
enemies[i].draw();
}
requestAnimationFrame(updateArea);
}