在检测下一步行动之前,我们如何等待一段时间?

时间:2014-04-01 00:31:00

标签: ios objective-c sprite-kit

基本上这就是我喜欢做的事情:

-(void)didBeginContact:(SKPhysicsContact *)contact
{
     uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);
     if (collision == (CNPhysicsCategoryCat|CNPhysicsCategoryBed)) {
         _catNode.userData = [@{@"catOnBed":@(YES)} mutableCopy];
         //Code here can let me wait for 3 seconds or something.
         (_catNode.userData[@"catOnBed"])?[self win]:[self lose];
     }
     if (collision == (CNPhysicsCategoryCat|CNPhysicsCategoryEdge)) {
         [self lose];
     }
}

所以我希望在接触发生后3秒钟完成检测。

我尝试了dispatch_time方法,它向我返回“断点2.1”。屏幕截图如下:

Breakpoint 2.1 Breakpoint 2.1

然后我也尝试了performSelector方法,它告诉我未声明的“detectContact ...”

detectContact

我也创建了方法,这里是证据。

evidence

然后我尝试了SKAction序列方法(我认为这个是关闭的)。它也失败了:

SKAction sequence

这是堆栈跟踪:

Stack Trace

4 个答案:

答案 0 :(得分:2)

您可以使用延迟任务!

int64_t delay = 3;
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC);
dispatch_after(time, dispatch_get_main_queue(), ^(void){
    // do whatever you want to do after 3 seconds.
});

答案 1 :(得分:2)

您可以使用-[NSObject performSelector:withObject:afterDelay]。有关更多信息,请查看documentation。基本上你的代码看起来像这样:

-(void)didBeginContact:(SKPhysicsContact *)contact {
    // Other code
    [self performSelector:@selector(detectContact) withObject:nil afterDelay:3];
}

- (void)detectContact {
    // Code to be execute after 3 second delay
}

方法detectContact将在3秒后被调用。

答案 2 :(得分:1)

像这样使用dispatch_time_t ......

double delaySeconds = 2.0;
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delaySeconds * NSEC_PER_SEC));
dispatch_after(time, dispatch_get_main_queue(), ^(void){
    (_catNode.userData[@"catOnBed"])?[self win]:[self lose];
});

答案 3 :(得分:1)

延迟推出新的SKAction

SKAction *delayedBlock = [SKAction sequence:@[[SKAction waitForDuration:2.0], 
                                              [SKAction runBlock:
^{
    // Perform action here.
}]]];

然后在相关的任何节点上运行它,可能是SKScene

// Assuming that self is the SKScene
[self runAction:delayedBlock];

我建议使用SKAction s而不是其他建议的替代方案,将其限制在SpriteKit的运行循环中。