SpriteKitをつかってカメレオンの色を変えるiPhoneアプリのサンプルコード。
今回使った画像
動かすとこんな感じなります
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface ChameleonScene : SKScene
@end
@implementation ChameleonScene
– (void)didMoveToView:(SKView *)view
{
[self createSceneContents];
}
– (void)createSceneContents
{
[self createColorSpace];
[self createChameleon];
}
– (void)createChameleon
{
SKSpriteNode *chameleon = [SKSpriteNode spriteNodeWithImageNamed:@”chameleon”];
chameleon.name = @”chameleon”;
chameleon.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
chameleon.color = [SKColor greenColor];
chameleon.colorBlendFactor = 1.0;
UIBezierPath *eyePath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(-7, –7, 14, 14)];
[eyePath appendPath:[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, –2, 8, 8)]];
eyePath.usesEvenOddFillRule = YES;
SKShapeNode *eye = [SKShapeNode node];
eye.path = eyePath.CGPath;
eye.position = CGPointMake(-25, 10);
eye.fillColor = [SKColor whiteColor];
[chameleon addChild:eye];
[self addChild:chameleon];
}
– (void)createColorSpace
{
UIBezierPath *ellipse = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(-50, –20, 100, 40)];
for (int i=0; i<4; i++) {
SKShapeNode *space = [SKShapeNode node];
space.name = @”space”;
space.path = ellipse.CGPath;
space.fillColor = [SKColor colorWithHue:0.2 * i + 0.2 saturation:0.8 brightness:0.8 alpha:1];
float x = (i % 2) * 300 + 100;
float y = (i / 2) * 150 + 80;
space.position = CGPointMake(x, y);
[self addChild:space];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
SKAction *move = [SKAction moveTo:p duration:1.0];
SKNode *chameleon = [self childNodeWithName:@”chameleon”];
[chameleon runAction:move completion:^{
[self changeColor];
}];
}
– (void)changeColor
{
SKSpriteNode *chameleon = (SKSpriteNode*)[self childNodeWithName:@”chameleon”];
[self enumerateChildNodesWithName:@”space” usingBlock:^(SKNode *node, BOOL *stop) {
if ([chameleon intersectsNode:node]) {
SKColor *color = [(SKShapeNode *)node fillColor];
SKAction *colorChange = [SKAction colorizeWithColor:color colorBlendFactor:0.5 duration:3.0];
[chameleon runAction:colorChange];
}
}];
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidAppear:(BOOL)animated
{
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[ChameleonScene alloc] initWithSize:spriteView.frame.size];
[spriteView presentScene:scene];
}
@end