我的应用程序使用 NSTimer
以固定间隔(亚秒)将自定义 SKNode
对象添加到 SKScene
。在某些时候,我希望计时器加速。这是我所做的(代码简化):
@interface MyScene : SKScene
@end
@implementation MyScene {
MyNode *node;
NSTimer *timer;
int speed;
}
- (id):initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
speed = 0.8f;
timer = [NSTimer = scheduledTimerWithTimeInterval:speed target:self selector:@selector(addNodeToScene) userInfo:nil repeats:YES];
}
}
- (id):addNodeToScene {
if (node != nil) {
[node removeFromParent];
node = nil;
}
CGPoint location = //random x y coordinates using arc4random()...
node = [[MyNode alloc] initAtLocation:location];
[self addChild:node];
}
// at some point I call this method (called regularly throughout life of app)
- (id):speedUp {
[timer invalidate];
timer = nil;
speed *= 0.9f;
timer = [NSTimer = scheduledTimerWithTimeInterval:speed target:self selector:@selector(addNodeToScene) userInfo:nil repeats:YES];
}
我注意到每次调用 speedUp
时都会有轻微的延迟。我是 Objective-C 的新手,所以不确定如何解决。在计时器上使用调度队列是否更有效,还是我不能避免这个问题,因为内部速度太快了?
我在仪器上运行时间分析,但没有突出显示 - 相反,我最重要的方法是 addNodeToScene
。
最佳答案
我的猜测是您在 -addNodeToScene
的正常工作之外调用了 -speedUp
。如果是这样,延迟很可能是因为您已经用完了之前的一些延迟,然后 -speedUp
使旧计时器无效并创建一个新计时器,这将启动所有延迟再次。每当您比上一个计时器触发超过 10% 时,您都会看到延迟。
我将尝试一些 ASCII 艺术来说明。 +
是计时器触发,*
是当您调用 -speedUp
并重置计时器时。
+---------+--------+---------+---------+---------+
+---------+---*--------+--------+--------+--------+
关于ios - NSTimer 更改间隔性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24714375/