如何制作动画按钮?

时间:2015-02-27 13:53:00

标签: ios objective-c sprite-kit

我在这样的场景中设置了一个按钮:

self.playButton = [SKSpriteNode spriteWithImageNamed:@"playbutton.png"];
self.playButton.size = CGSizeMake(100,100);
self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), 100);
[self addChild:self.playButton];

然后在touchesBegan:

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

if([self.playButton containsPoint:location]){
    self.playButton.texture = [SKTexture textureWithImageNamed:@"playbuttonpressed.png"];
    [self.playButton runAction: [self touchButtonAction]];
}

然后在touchesEnded:

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

if([self.playButton containsPoint:location]){
    self.playButton.texture = [SKTexture textureWithImageNamed:@"playbutton.png"];
    [self.view presentScene:self.nextScene transition:self.sceneTransition];

}

然后在touchButtonAction中:

SKAction *toSmall = [SKAction scaleBy:0.8 duration:0.1];
return toSmall;

问题出在这里:当我点击按钮时,会在动作完成之前调用touchesEnded,这会导致动画效果不完整(看起来很迟钝)。如何在转换之前创建一个完成动画的按钮?

1 个答案:

答案 0 :(得分:1)

有几种方法可以实现您想要的效果。其中一个是使用块。

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

if([self.playButton containsPoint:location]){

    SKAction *block0 = [SKAction runBlock:^{
        self.playButton.texture = [SKTexture textureWithImageNamed:@"playbuttonpressed.png"];
        [self.playButton runAction: [self touchButtonAction]];
    }];

    SKAction *wait0 = [SKAction waitForDuration:1.0]; // <- however long it takes for the animation to complete

    SKAction *block1 = [SKAction runBlock:^{
        self.playButton.texture = [SKTexture textureWithImageNamed:@"playbutton.png"];
        [self.view presentScene:self.nextScene transaction:self.sceneTransaction];
    }];

    [self runAction:[SKAction sequence:@[block0, wait0, block1]]];
}

有关使用块的更多信息,请阅读Apple Blocks Programming Guide