我如何创建一个每两秒触发一次的计时器,使我屏幕上的 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 中不要使用 NSTimer
、performSelector: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/