这是一个如何在 SpriteKit 中实现倒数计时器的示例。
首先,声明一个创建 1) 显示剩余时间的标签节点和 2) 更新标签的适当操作的方法,等待一秒钟,然后冲洗/起泡/重复
- (void) createTimerWithDuration:(NSInteger)seconds position:(CGPoint)position andSize:(CGFloat)size {
// Allocate/initialize the label node
countDown = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
countDown.position = position;
countDown.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeLeft;
countDown.fontSize = size;
[self addChild: countDown];
// Initialize the countdown variable
countDownInt = seconds;
// Define the actions
SKAction *updateLabel = [SKAction runBlock:^{
countDown.text = [NSString stringWithFormat:@"Time Left: %ld", countDownInt];
--countDownInt;
}];
SKAction *wait = [SKAction waitForDuration:1.0];
// Create a combined action
SKAction *updateLabelAndWait = [SKAction sequence:@[updateLabel, wait]];
// Run action "seconds" number of times and then set the label to indicate
// the countdown has ended
[self runAction:[SKAction repeatAction:updateLabelAndWait count:seconds] completion:^{
countDown.text = @"Time's Up";
}];
}
然后使用持续时间(以秒为单位)和标签的位置/大小调用该方法。
CGPoint location = CGPointMake (CGRectGetMidX(self.view.frame),CGRectGetMidY(self.view.frame));
[self createTimerWithDuration:20 position:location andSize:24.0];