adam adam - 1 year ago 142
Objective-C Question

SKShapeNode - Animate color change

I'm working on a game with SpriteKit. I'm drawing a shape with SKShapeNode. Now I want to animate its colour change but the SKActions is not working for SKShapeNode. Is there any way to do this or I have to use a different approach?

Thank you.


Thanks to LearnCocos2D I was able to come up with this quick (and totally not perfect) solution.

int groundChangeInterval = 5;
SKColor *originalColor = [SKColor colorWithRed:0.92 green:0.87 blue:0.38 alpha:1.0];
SKColor *finalColor = [SKColor colorWithRed:0.29 green:0.89 blue:0.31 alpha:1.0];

CGFloat red1 = 0.0, green1 = 0.0, blue1 = 0.0, alpha1 = 0.0;
[originalColor getRed:&red1 green:&green1 blue:&blue1 alpha:&alpha1];

CGFloat red2 = 0.0, green2 = 0.0, blue2 = 0.0, alpha2 = 0.0;
[finalColor getRed:&red2 green:&green2 blue:&blue2 alpha:&alpha2];

SKAction *changeGroundColor = [SKAction customActionWithDuration:groundChangeInterval actionBlock:^(SKNode *node, CGFloat elapsedTime) {
CGFloat step = elapsedTime/groundChangeInterval;

CGFloat red3 = 0.0, green3 = 0.0, blue3 = 0.0;
red3 = red1-(red1-red2)*step;
green3 = green1-(green1-green2)*step;
blue3 = blue1-(blue1-blue2)*step;

[(SKShapeNode*)node setFillColor:[SKColor colorWithRed:red3 green:green3 blue:blue3 alpha:1.0]];
[(SKShapeNode*)node setStrokeColor:[SKColor colorWithRed:red3 green:green3 blue:blue3 alpha:1.0]];

I only needed to fade two specific colours so it is not a universal solution but it is enough for now.


Answer Source

Use customActionWithDuration:block: and change the fillColor or strokeColor properties.

I suppose the colorize actions won't work because SKShapeNode has no color property. It's worth a try to add this property to the class in a subclass or category and redirect it to fillColor or strokeColor or both.