使用按钮动画加载场景异步时出现问题

时间:2014-09-12 09:42:13

标签: objective-c sprite-kit dispatch-async

我试图在主菜单中实现动画启动按钮。因为我的场景需要一段时间来加载,我想用这个按钮动画来弥补等待时间。不幸的是动画没有开始。我的代码有什么问题?

-(void)buttonAnimation{
    SKAction *HUDzoom = [SKAction scaleTo:3 duration:1];
    SKAction *HUDzoomOut = [SKAction scaleTo:1.0 duration:1];
    SKAction *HUDAnimation = [SKAction sequence:@[HUDzoom, HUDzoomOut]];

    [self.startButton runAction:[SKAction repeatActionForever:HUDAnimation]];
}

-(void)loadScene{
    SKScene *restart = [[Level_1 alloc] initWithSize:self.size];
    [self.view presentScene:restart];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];

    SKNode *node = [self nodeAtPoint:location];

    if ([node.name isEqualToString:@"startLevel1"]){

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                [self loadScene];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self buttonAnimation];
            });
        });

    }
}

1 个答案:

答案 0 :(得分:3)

那是因为你以异步方式加载场景,只有在完成后才会异步启动按钮动画:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    // loading the scene
    [self loadScene];

    // when scene has finished loading, animate the button asynchronically
    // (this makes no sense)
    dispatch_async(dispatch_get_main_queue(), ^{
        [self buttonAnimation];
    });
});

相反,你应该开始动画,然后异步加载场景。

[self buttonAnimation];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [self loadScene];
});

该按钮由Sprite Kit动作设置动画,而您可以异步启动动画,它不会异步制作整个动画。相反,您只需要确保任何阻塞方法(如loadScene)以异步方式运行。