fitness23 Posted June 3, 2016 Share Posted June 3, 2016 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); WombatTurkey 1 Link to comment Share on other sites More sharing options...
shohan4556 Posted June 4, 2016 Share Posted June 4, 2016 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. WombatTurkey 1 Link to comment Share on other sites More sharing options...
WombatTurkey Posted June 4, 2016 Share Posted June 4, 2016 @shohan4556 I never knew Phaser had a ArrayUtils method until now Link to comment Share on other sites More sharing options...
fitness23 Posted June 4, 2016 Author Share Posted June 4, 2016 @shohan4556 Fantastic! The first example worked and is alot smaller and concise. Thank you so much Link to comment Share on other sites More sharing options...
ecv Posted June 4, 2016 Share Posted June 4, 2016 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. Link to comment Share on other sites More sharing options...
Recommended Posts