ok…so i’m randomly generating a level in a class and then pass it to the game.
The problem is that when i generate the level sometimes it gets stuck in a loop ( due to the checks i do when i generate it). I’ve tried to reduce the number of freezes by modifying the code..but it still gets stuck in like 1~2 % if the cases.
in RandomLevel i have this:
-(void)positionMonsters:(int)nrM{
int nrH=[randomHero count];
int rdm;
CGPoint randPt;
BOOL is;
while ([randomMonsters count]!=nrM) {
rdm=arc4random()%(nrH-1);
if (rdm!=nrH-1) {
randPt=random_on_line([[randomHero objectAtIndex:rdm]position], [[randomHero objectAtIndex:rdm+1]position ], CCRANDOM_0_1());
}else{
randPt=random_on_line([[randomHero objectAtIndex:rdm]position], [[randomHero objectAtIndex:0]position ], CCRANDOM_0_1());
}
is=NO;
for (Monster *mob in randomMonsters) {
if (ccpFuzzyEqual(randPt, mob.position, 40)) {
is=YES;
break;
}
}
if (!is) {
Monster *mob=[[Monster alloc]initWithPosition:randPt];
[randomMonsters addObject:mob];
}
}
}
let me walk you through the code :
so i get the count of heros (how many there), as long as there aren’t as many monsters as i want to make, i chose a random line between 2 consecutive heros and generate a point on that line, then i check if the point generated is close to any other (i don’t want the to overlap).. if it is then it starts the loop again, if it’s not i add it to the random mobs
it get’s stuck when i check if the mob overlaps another …but i shouldn’t because the heros are always at least 200 px apart and i only make a handfull of mobs.
in my GameScene i do this:
-(id)init{
//stuff stuff
RandomLevel *rlv=[[RandomLevel alloc]initWithHeros:6 andMonsters:6]; *****
heros=rlv.randomHeros;
mobs=rlv.randomMonsters;
}
what i want is to stop / cancel the ***** line and try to get a random level again …as i said.. this only happens only 1% of the cases so it wouldn’t be such a big deal if the game “freezes” for 2 sec every week ..or something
Could you use
performSelector:withDelayand cancel it within your loop if before it ends?