ios - SpriteKit - 创建一个计时器

标签 ios objective-c timer sprite-kit

我如何创建一个每两秒触发一次的计时器,使我屏幕上的 HUD 上的分数增加 1?这是我的 HUD 代码:

    @implementation MyScene
{
    int counter;
    BOOL updateLabel;
    SKLabelNode *counterLabel;
}

-(id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
        counter = 0;

        updateLabel = false;

        counterLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
        counterLabel.name = @"myCounterLabel";
        counterLabel.text = @"0";
        counterLabel.fontSize = 20;
        counterLabel.fontColor = [SKColor yellowColor];
        counterLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeCenter;
        counterLabel.verticalAlignmentMode = SKLabelVerticalAlignmentModeBottom;
        counterLabel.position = CGPointMake(50,50); // change x,y to location you want
        counterLabel.zPosition = 900;
        [self addChild: counterLabel];
    }
}

最佳答案

在 Sprite Kit 中不要使用 NSTimerperformSelector:afterDelay: 或 Grand Central Dispatch(GCD,即任何 dispatch_. .. 方法),因为这些计时方法忽略了节点、场景或 View 的 paused 状态。此外,您不知道它们在游戏循环的哪个点执行,这可能会导致各种问题,具体取决于您的代码实际执行的操作。

在 Sprite Kit 中执行基于时间的事情的唯一两种认可方法是使用 SKScene update: 方法和使用传入的 currentTime 参数来跟踪时间。

或者更常见的是,您将只使用以等待操作开始的操作序列:

id wait = [SKAction waitForDuration:2.5];
id run = [SKAction runBlock:^{
    // your code here ...
}];
[node runAction:[SKAction sequence:@[wait, run]]];

并重复运行代码:

[node runAction:[SKAction repeatActionForever:[SKAction sequence:@[wait, run]]]];

或者,您也可以使用 performSelector:onTarget: 代替 runBlock:,或者如果您需要模仿,也可以使用 customActionWithDuration:actionBlock: SKScene update: 方法,不知道如何将其转发到节点或转发不方便的地方。

参见 SKAction reference了解详情。


更新:使用 Swift 的代码示例

swift 5

 run(SKAction.repeatForever(SKAction.sequence([
     SKAction.run( /*code block or a func name to call*/ ),
     SKAction.wait(forDuration: 2.5)
     ])))

swift 3

let wait = SKAction.wait(forDuration:2.5)
let action = SKAction.run {
    // your code here ...
}
run(SKAction.sequence([wait,action]))

swift 2

let wait = SKAction.waitForDuration(2.5)
let run = SKAction.runBlock {
    // your code here ...
}
runAction(SKAction.sequence([wait, run]))

并重复运行代码:

runAction(SKAction.repeatActionForever(SKAction.sequence([wait, run])))

关于ios - SpriteKit - 创建一个计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23978209/

相关文章:

ios - 如何在使用另一个 UISwitch 时更新一个 UISwitch

ios - Storyboard的子类 ViewController

objective-c - UITableView 滑动删除 : how to customize button and action?

ios - UITableView 上未调用长按手势

c# - 1 综合计时器 vs. 多个计时器,每个对象一个计时器

ios - 在 IOS 5 上将应用程序限制为特定方向

ios - 倒计时和关闭模态视图

ios - Swift:尝试从数据源结构中检索数据

java - 正确更新 Swing 组件?

java - 如何创建定时器功能?