我想在简单的SpriteKit游戏中添加一个计时器。使用现有答案中建议的代码(" Spritekit - 创建计时器")会导致5个错误(下面的评论)。也许还有其他想法!
非常感谢!
这是我的.m文件:
@implementation GameScene {
BOOL updateLabel;
SKLabelNode *timerLabel;
}
int timer;
- (id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
self.backgroundColor = [SKColor whiteColor];
timer = 0;
updateLabel = false;
timerLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
timerLabel.text = @"0";
timerLabel.fontSize = 48;
timerLabel.fontColor = [SKColor greenColor];
timerLabel.position = CGPointMake(700,50);
[self addChild: timerLabel];
}
return self;
}
-(void) didMoveToView:(SKView *)view {
}
以下代码给我带来了麻烦:
id wait = [SKAction waitForDuration:1.0];//Redefinition of 'wait' as different kind of symbol
id run = [SKAction runBlock:^{//Initializer element is not a compile-time constant
timer ++;
updateLabel = true;
}];
[node runAction:[SKAction repeatActionForever:[SKAction sequence:@[wait, run]]];//1. Expected identifier or '('; 2. Use of undeclared identifier 'node'; 3. Collection element of type 'pid_t (int *)' is not an Objective-C object
-(void)update:(CFTimeInterval)currentTime {
if(updateLabel == true){
timerLabel.text = [NSString stringWithFormat:@"%i",timer];
updateLabel = false;
}
}
@end
答案 0 :(得分:0)
int timer = 0;
SKLabelNode timerLabel;
- (id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
SKAction *wait = [SKAction waitForDuration:1];
SKAction *performSelector = [SKAction performSelector:@selector(timerLabel) onTarget:self];
SKAction *removeChild = [SKAction runBlock:^{
[timerLabel removeFromParent];
}];
SKAction *increaseTimer = [SKAction runBlock:^{
timer++;
}];
SKAction *sequence = [SKAction sequence:@[removeChild, performSelector, wait, increaseTimer]];
SKAction *repeat = [SKAction repeatActionForever:sequence];
[self runAction:repeat];
}
return self;
}
-(void)timerLabel
{
timerLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
timerLabel.text = [NSString stringWithFormat:@"%i", timer];
timerLabel.fontSize = 48;
timerLabel.fontColor = [SKColor greenColor];
timerLabel.position = CGPointMake(700,50);
[self addChild: timerLabel];
}
尝试使用执行选择器进行调用。我希望这会奏效。我没有测试。