I want to run an action and go on go on processing game logic at the same time, but action is interrupted when the process is going on. I tried to use thread, but I couldn’t make it work. When it’s not needed to process game logic the sprites move as I expected, but when it’s needed to make some operations during action, the action is interrupted during the operation time. After the operation is ended, the action is going on.
What am I doing wrong?
I call a selector as follows – the selector starts the action.
[NSThread detachNewThreadSelector:@selector(moveSprite:)
toTarget:self
withObject:[NSDictionary dictionaryWithObjectsAndKeys:
sprite, @"sprite",
[NSValue valueWithCGPoint:pos], @"pos",
nil]];
-(void) moveSprite: (NSDictionary*) parameters {
CCSprite *sprite = [parameters objectForKey:@"sprite"];
CGPoint pos = [[parameters objectForKey:@"pos"] CGPointValue];
id actionMove = [CCMoveTo actionWithDuration:0.4f position:pos];
id actionMoveDone = [CCCallFuncND actionWithTarget:self selector:@selector(removeSprite:data:) data:(__bridge void*)sprite];
[sprite runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];
}
After the action ends I remove the sprite by following method.
-(void) removeSprite: (id)sender data:(void*)data {
CCSprite *sprite = (__bridge CCSprite*)data;
[self removeChild:sprite cleanup:YES];
}
First, it makes no sense to create actions in a separate thread. The actions are added to the node, and the node along with its actions are updated on the main thread.
You should also know that threading will only help you if the device has two or more CPU cores. On a single core device (iPhone 4 or earlier, iPod Touch 4 or earlier, iPad 1) running a separate thread that performs heavy duty operations will still slow down if not halt the main thread.
If your game logic is that heavy that it actually halts the screen updates, you need to optimize whatever you’re doing. You could spread the calculation across multiple frames, profile to see if you can optimize, or if you’re using a brute force approach research more clever, less straightforward but faster algorithms.