如何创建一个每两秒触发一次的计时器,以使屏幕上显示的HUD得分增加一?这是我为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];
}
}
在雪碧包不使用 NSTimer
,performSelector:afterDelay:
或大中央调度(GCD,即任何dispatch_...
方法),因为这些时间的方法忽略了一个节点,现场的或视图的paused
状态。此外,您不知道它们在游戏循环中的哪一点执行,这可能会导致各种问题,具体取决于您的代码实际执行的操作。
在Sprite Kit中执行基于时间的某些操作的唯一批准的两种方法是使用SKSceneupdate:
方法和使用传入的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:
,如果您需要模仿SKScene方法并且不知道如何将其转发到节点或转发不便的地方,也可以使用代替runBlock:
或使用a 。customActionWithDuration:actionBlock:
update:
有关详细信息,请参见SKAction参考。
更新:使用Swift的代码示例
迅捷5
run(SKAction.repeatForever(SKAction.sequence([
SKAction.run( /*code block or a func name to call*/ ),
SKAction.wait(forDuration: 2.5)
])))
迅捷3
let wait = SKAction.wait(forDuration:2.5)
let action = SKAction.run {
// your code here ...
}
run(SKAction.sequence([wait,action]))
迅捷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])))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句