fuzzygoat
fuzzygoat

Reputation: 26223

Fade between two different SKTextures on SKSpriteNode

Does anyone know if there is a way to fade (over time) between two different SKTextures on an SKSpriteNode. I am assuming that you can't do this directly and plan to use a duplicate child sprite with a higher ZPosition to realise the fade, but I just wanted to check that there was not some method using SKAction(s) that I had over looked.

Upvotes: 3

Views: 1287

Answers (1)

dave
dave

Reputation: 1180

The following code should address this issue assuming the new texture fits overtop of the old one (it doesn't fade out the previous texture, but simply fades in the new one on top). I've left out minor implementation details such as timing mode.

-(void) fadeTexture:(SKTexture *)newTexture ontoSpriteNode:(SKSpriteNode *)referenceSpriteNode withDuration:(CFTimeInterval)duration {

    SKSpriteNode * fadeInSprite = [self fadeInSpriteWithTexture:newTexture referenceSpriteNode:referenceSpriteNode];

    [[referenceSpriteNode parent] addChild:fadeInSprite];
    [fadeInSprite runAction:[SKAction sequence:@[
        [SKAction fadeAlphaTo:1 duration:duration],
        [SKAction runBlock:^{
            [fadeInSprite removeFromParent];
            [referenceSpriteNode setTexture:newTexture];
        }]
    ]]];
}

-(SKSpriteNode *) fadeInSpriteWithTexture:(SKTexture *)newTexture referenceSpriteNode:(SKSpriteNode *)referenceSpriteNode {

    SKSpriteNode * fadeInSprite = [SKSpriteNode spriteNodeWithTexture:newTexture size:[referenceSpriteNode size]];
    [fadeInSprite setAlpha:0];
    [fadeInSprite setAnchorPoint:[referenceSpriteNode anchorPoint]];
    [fadeInSprite setPosition:[referenceSpriteNode position]];
    return fadeInSprite;
}

Upvotes: 2

Related Questions