Jump to content

¿How to run a pool of on-screen enemies?


pix0l
 Share

Recommended Posts

Hello!

 

I'm learning to make games using phaser. I made the first tutorial and after that I discover the HTML 5 Shoot 'em Up in an Afternoon (great shortbook btw) and I kinda completed it, but i'm stuck at the "challenges" at the end. I understand what I have to do but I lack the tools to do it and I am a total noob at reading documentation so i'm asking for a bit of help here. I'm trying to do the bomb but I haven't found a way to hit all the enemies on the screen at the same time because I don't know how to go form the first enemy on screen to the last. I suppose there is a pool function for that but I can't seem to find it. So here I am, asking for advice. Thanks in advance! :)

Link to comment
Share on other sites

A pool is a way of creating all the objects you'll need beforehand (in some cases making the pool a bit more flexible by allowing new objects to be created on demand when the pool is empty) and then just turning them on and off as needed. This is great for stuff like bullets, where you'd create say 20 bullet sprites, then just recycle those when you fire - reviving them when they appear at the end of the gun barrel, and killing them when they fly off the screen or hit an object. The idea behind a pool is that creating and destroying objects is far less efficient than recycling ones that already exist but are just temporarily hidden and deactivated.

 

What you're looking for an 'iterator' - basically a way to go through a list of objects and do something to each one. In JavaScript an iterator can be as simple as an array of enemies and a for loop:

for (var i = 0; i < enemies.length; i++) {  if (enemies[i].alive) {    enemies[i].kill();  }}

A more modern way to do this is via Array.forEach:

enemies.forEach(function(enemy) {  if (enemy.alive) {    enemy.kill();  }});

Better still, Groups in Phaser have some handy iterator methods such as forEachAlive, forEachExists and forEachDead which will work in much the same way:

enemies.forEachAlive(function(enemy) {  enemy.kill();});

From here you can do whatever you want - you could for instance, use Phaser.Math.distance to set a maximum range for the bomb:

enemies.forEachAlive(function(enemy) {  // If the enemy is within a 200 pixel radius of the bomb, kill it  if (Phaser.Math.distance(bomb.x, bomb.y, enemy.x, enemy.y) < 200) {    enemy.kill();  }});
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...