简体   繁体   中英

How can I add a delay before it continues

Is there a way in the normal obj-c or cocos2d to make a delay inside a if-else block? Like

if ([self isValidTileCoord:cTileCoord] && ![self isWallAtTileCoord:cTileCoord])
{
    [self addChild:circle0];
    //wait two seconds
    //perform another task
}

Just a simple lag to wait between two tasks, or stalling an action. Is there any simple way to do this?

There are many ways to do this. I would use GCD

if ([self isValidTileCoord:cTileCoord] && ![self isWallAtTileCoord:cTileCoord])
{
    [self addChild:circle0];
    //wait two seconds
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{
        //perform another task;
    });
}

You can use the performSelector: withObject: afterDelay: method to delay tasks:

if ([self isValidTileCoord:cTileCoord] && ![self isWallAtTileCoord:cTileCoord])
{
    [self addChild:circle0];
    //wait two seconds
    [self performSelector:@selector(continueTask) withObject:nil afterDelay:2.0];

}

And in the selector method:

-(void)continueTask
{
    //perform another task
}

Inside the cocos2d you can also run an Action on the node like,

[self runAction:[CCSequence actions:[CCDelayTime actionWithDuration:2.0],[CCCallFunc actionWithTarget:self selector:@selector(anothertaks)],nil]];

Perform selector will also work but the problem is that all the schedulers of cocos2D get paused when the app go to background but on the other side perform selector will still count the time, so some time it create task,animation,etc syncing problems.

Perform selector:

    [self performSelector:@selector(continueTask) withObject:nil afterDelay:2.0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM