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?


/* 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();

// do stuff

or try this

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

    // 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();

	// do stuff

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.