I am making a simon game in objective-c using sprite kit in Xcode. What I am trying to accomplish is to pick random number, add it to the sequence, fadeout, pick next random number... what happens when I run this code is that all the tiles in the sequence fadeout then back in at exactly the same time.
Here is my code:
-(void) sequence
{
NSMutableArray *sequenceArray = [[NSMutableArray alloc] initWithCapacity:50];
int randomNumber;
SKAction *fadeOut = [SKAction fadeOutWithDuration: 1]; //color of tile fades out
SKAction *fadeIn = [SKAction fadeInWithDuration: 1]; //color of tile fades in
SKAction *pulse = [SKAction sequence:@[fadeOut,fadeIn]]; //holds a sequence so tile fades out then fades in
CFTimeInterval startTime;
float elapsedTime;
for(int i = 0; i<level+1; i++)
{
startTime = CFAbsoluteTimeGetCurrent();
randomNumber=[self getRandomNumber]; //random number is picked
if(randomNumber==0)
{
sequenceArray[i]=blueBox;
}
else if(randomNumber==1)
{
sequenceArray[i]=redBox;
}
else if(randomNumber==2)
{
sequenceArray[i]=yellowBox;
}
else if(randomNumber==3)
{
sequenceArray[i]=greenBox;
}
[sequenceArray[i] runAction:[SKAction repeatAction:pulse count:1]]; //for each tile in the sequence the color fades
//out then back in
elapsedTime = CFAbsoluteTimeGetCurrent()-startTime; //trying to pause the loop so the sequence can finish before the
//next random number is picked
while(elapsedTime<.5)
{
elapsedTime = CFAbsoluteTimeGetCurrent()-startTime;
NSLog(@"elapsed time %f", elapsedTime);
}
}
}
Ok I have tried to implement some of the suggestions below. I still am running into errors, for example now the sequenceArray[index] at index=0 is out of bounds.
Here is my new code:
-(void)doLoop:(int)index
limit:(int)limit
sprite:(SKSpriteNode*) sprite
body:(void(^)(int))body
{
body(index);
index++;
if(index<level+1)
{
SKAction *loopAction;
[self runAction:loopAction completion:^{
[self doLoop:index limit:limit sprite:sprite body:body];
}];
}
}
-(void) sequence
{
NSMutableArray *sequenceArray = [[NSMutableArray alloc] initWithCapacity:50];
int index = 0;
SKAction *fadeOut = [SKAction fadeOutWithDuration: 1]; //color of tile fades out
SKAction *fadeIn = [SKAction fadeInWithDuration: 1]; //color of tile fades in
SKAction *pulse = [SKAction sequence:@[fadeOut,fadeIn]]; //holds a sequence so tile fades out then fades in
[self doLoop:0 limit:level+1 sprite:sequenceArray[index] body:^(int index){
int randomNumber=[self getRandomNumber]; //random number is picked
if(randomNumber==0)
{
sequenceArray[index]=blueBox;
}
else if(randomNumber==1)
{
sequenceArray[index]=redBox;
}
else if(randomNumber==2)
{
sequenceArray[index]=yellowBox;
}
else if(randomNumber==3)
{
sequenceArray[index]=greenBox;
}
[sequenceArray[index] runAction:pulse]; //for each tile in the sequence the color fades
//out then back in
NSLog(@"fadeout");
}];
}