fitness23

Choose 1 random sprite in a group with a particular property

Recommended Posts

How can I choose 1 random sprite in a group that has a particular property with a value?

So for example the group is called "enemyGroup" and I want to choose a random sprite in their which has the property of "inAttackZone" which is set to yes?

Something like this?

enemyGroup.random().forEachAlive(function(enemy.attackZone='yes')
{

/* Now do something with enemy */

}, this);  

 

Share this post


Link to post
Share on other sites

you can try something like this,

var mychild = myGroup.getRandom();

if(mychild.attackZone==true){
// do stuff
}

or try this

Phaser.ArrayUtils.shuffle(myGroup); // shuffle group here
myGroup.updateZ(); // apply the changes

myGroup.forEach(function(enemy){
   if(enemy.attaxkZone==true){
    // dostuff
    // break 
   }
});

 Hope this helps.

Share this post


Link to post
Share on other sites

I'd like to point out the difference in the proposed methods (from my limited understanding):

First one will pick one such element of the group, check whether its property matches, and if it doesn't it won't do anything.

Second one will shuffle the elements, and I'm afraid the change is permanent. So while it works, there could be a number of reasons you might not want to go with this one.

While you could go with looping the first method, getting randoms and checking, such as here:

syntax might not be accurate:

var mychild;
while (true) { //Ugly, I know.
	mychild = myGroup.getRandom();

	if(mychild.attackZone==true){
	// do stuff
	break;
	}
}

this will fall into an infinite loop if none of the elements' property matches. So perhaps setting a for loop with a reasonable limit, like 100 times the group length would be more appropriate.

But it looks like the most appropriate solution would be to use the proposed 2nd method and keep a copy of the original group (in case you need to preserve its order). Now, I can't give you code for this, because I honestly don't know how Phaser groups behave. While the ArrayUtils.shuffle function seems to take arrays, I have no idea if using myOriginalGroup=myGroup.slice(); will work, or whether a simple assignment will create a true copy of a group instead of a reference.

@fitness23: I just thought I would mention it, because the first method might not be exactly what you're looking for.

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.