Hamish
Hamish

Reputation: 80781

Objective c - Animate background colour of SKScene

How would you go about animating the background colour of an SKScene? I've tried a UIView animate, but not surprisingly it didn't work. Is there an equivalent to do this in Sprite-Kit?

I'm looking for something like this, but for Sprite-Kit:

[UIView animateWithDuration:0.25 animations:^{
   self.backgroundColor = [UIColor redColor];
}];

At the moment, as a work around I have overlayed a UIView over the SKView, but I would like something more flexible.

I am relatively new to Sprite-Kit, so appologies if this is extremely simple to do!

At the moment I have:

-(id) initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        _bg = [SKSpriteNode spriteNodeWithColor:[SKColor colorWithRed:0.13 green:0.13 blue:0.13 alpha:1] size:self.size];
        _bg.position = CGPointMake(self.size.width/2, self.size.height/2);
        [self addChild:_bg];
    }
    return self;
}

-(void) colorise :(UIColor*)color {
    [_bg runAction:[SKAction colorizeWithColor:color colorBlendFactor:_bg.colorBlendFactor duration:1]];
}

Also after initialising the SKView, I'm setting the color of the bg sprite depending on an NSUserDefault Value.

 if ([[NSUserDefaults standardUserDefaults] integerForKey:@"currGameMode"] == 0) {
((bubbleAnimation2*)_bubbleEffectView.scene).bg.color = [UIColor colorWithRed:0.13 green:0.13 blue:0.13 alpha:1];}
else {((bubbleAnimation2*)_bubbleEffectView.scene).bg.color = [UIColor colorWithRed:0.25 green:0.13 blue:0.13 alpha:1];}

Thanks!

Upvotes: 2

Views: 1299

Answers (1)

Hamish
Hamish

Reputation: 80781

Well, I came up with a completely over-engineered solution! I have an array of background sprites and I clone the original sprite and change it's color and then animate it in.

Here's my code:

-(void) colorise :(UIColor*)color {
   // [_bg runAction:[SKAction colorizeWithColor:color colorBlendFactor:_bg.colorBlendFactor duration:1]];
    if ([_bgObjects count] != 0) {
        SKSpriteNode* newBg = [[_bgObjects objectAtIndex:0] copy];
        newBg.color = color;
        newBg.alpha = 0;
        [self insertChild:newBg atIndex:1];
        [newBg runAction:[SKAction fadeAlphaTo:1 duration:0.5]];
        [_bgObjects addObject:newBg];

        for (int i = 0; i < ([_bgObjects count]-1); i++) {
            [[_bgObjects objectAtIndex:i] runAction:[SKAction fadeAlphaTo:0 duration:0.5]];
        }

    }
}

-(void) update:(NSTimeInterval)currentTime {
    if ([_bgObjects count] > 1) {

    NSMutableArray* toDelete = [NSMutableArray arrayWithObjects: nil];

    for (SKSpriteNode* bg in _bgObjects) {
        if ((bg.alpha == 0) && !bg.hasActions) {
            [bg removeFromParent];
            [toDelete addObject:bg];
        }} [_bgObjects removeObjectsInArray:toDelete];
    }
}

Upvotes: 1

Related Questions