Skip to content

Instantly share code, notes, and snippets.

@warpling
Created March 9, 2017 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save warpling/fde6a753d6c3ef35b22b00aff4698a4b to your computer and use it in GitHub Desktop.
Save warpling/fde6a753d6c3ef35b22b00aff4698a4b to your computer and use it in GitHub Desktop.
//
// SKAction+FadeColorAction.h
//
#import <SpriteKit/SpriteKit.h>
@interface SKAction (FadeColorAction)
+ (SKAction*) fadeColorFrom:(SKColor*)fromColor toColor:(SKColor*)toColor duration:(CGFloat)duration;
@end
//
// SKAction+FadeColorAction.m
//
#import "SKAction+FadeColorAction.h"
// Note: It's probably best to relocate this to whereever you typically define macros
#define lerp(a, b, fraction) ((((b) - (a)) * (fraction)) + (a))
@implementation SKAction (FadeColorAction)
// Modified from: http://stackoverflow.com/a/27825008/522498
+ (SKAction*) fadeColorFrom:(SKColor*)fromColor toColor:(SKColor*)toColor duration:(CGFloat)duration {
// get the Color components of col1 and col2
CGFloat r1 = 0.0, g1 = 0.0, b1 = 0.0, a1 = 0.0;
CGFloat r2 = 0.0, g2 = 0.0, b2 = 0.0, a2 = 0.0;
[fromColor getRed:&r1 green:&g1 blue:&b1 alpha:&a1];
[toColor getRed:&r2 green:&g2 blue:&b2 alpha:&a2];
return [SKAction customActionWithDuration:duration actionBlock:^(SKNode *node, CGFloat elapsedTime) {
CGFloat fraction = elapsedTime / duration;
SKColor *interpolatedColor = [SKColor colorWithRed:lerp(r1,r2,fraction)
green:lerp(g1,g2,fraction)
blue:lerp(b1,b2,fraction)
alpha:lerp(a1,a2,fraction)];
[(SKShapeNode*)node setFillColor:interpolatedColor];
[(SKShapeNode*)node setStrokeColor:interpolatedColor];
}];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment