Game Development Reference
In-Depth Information
nore. Cocos2d doesn't schedule the selector a second time, but merely updates the
scheduled selector's interval. The spidersUpdate : method, shown in Listing
4-10 , randomly picks one of the existing spiders, checks whether it's idle, and lets it fall
down the screen by using a sequence of actions.
Listing 4-10 . The spidersUpdate: Method Frequently Lets a Spider Fall
-(void) spidersUpdate:(ccTime)delta
// Try to find a spider which isn't currently moving.
for (int i = 0; i < 10; i++)
int randomSpiderIndex = CCRANDOM_0_1() * spiders.count;
CCSprite* spider = [spiders objectAtIndex:randomSpiderIndex];
// If the spider isn't moving it won't have any running actions.
if (spider.numberOfRunningActions == 0)
// This is the sequence which controls the spiders' movement
[self runSpiderMoveSequence:spider];
// Only one spider should start moving at a time.
I don't let any listing pass without some curiosity, do I? In this case, you might wonder
why you're iterating exactly ten times to get a random spider. The reason is that you
don't know if the randomly generated index will get you a spider that isn't moving
already, so you want to be reasonably sure it eventually picks a spider that's currently
idle. If after ten tries—and this number is arbitrary—you didn't have the luck to get an
idle spider chosen randomly, simply skip this update and wait for the next.
You could brute-force your way and just keep trying to find an idle spider using a do/
while loop. However, it's possible that all spiders could be moving at the same time,
because this depends on design parameters such as the frequency with which new
spiders are being dropped. In that case, the game would simply lock up, looping end-
lessly trying to find an idle spider. Moreover, I'm not so keen on trying too hard; it
Search Nedrilad ::

Custom Search