赤、緑、青、黄色のボタンを押すと、同じ色の線の上をマーカーが通っていくiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@import SpriteKit;
@interface RouteScene : SKScene
@property (nonatomic, strong) NSMutableArray *pathArr;
@end
@implementation RouteScene
– (void)didMoveToView:(SKView *)view
{
self.backgroundColor = [SKColor colorWithWhite:0.2 alpha:1];
[self createRoute];
[self createTag];
}
– (void)createRoute
{
SKNode *routeMap = [SKNode node];
routeMap.name = @”routeMap”;
routeMap.position = CGPointMake(30, CGRectGetMaxY(self.frame) – 300);
[self addChild:routeMap];
self.pathArr = [NSMutableArray array];
float l = 80;
// route point
int p [] = {0,0, 1,1, 2,1, 3,0,
0,1, 1,3, 2,2, 3,2,
0,2, 1,2, 2,1, 3,1,
0,3, 1,0, 2,3, 3,3};
for (int i=0; i<4; i++) {
UIBezierPath *path = [UIBezierPath bezierPath];
int idx = i * 8;
[path moveToPoint:CGPointMake(p[idx] * l, p[idx+1] * l)];
[path addLineToPoint:CGPointMake(p[idx+2] * l, p[idx+3] * l)];
[path addLineToPoint:CGPointMake(p[idx+4] * l, p[idx+5] * l)];
[path addLineToPoint:CGPointMake(p[idx+6] * l, p[idx+7] * l)];
SKShapeNode *n = [SKShapeNode node];
n.name = [NSString stringWithFormat:@”route%d”, i];
n.path = path.CGPath;
n.strokeColor = [SKColor colorWithHue:i *0.2 saturation:0.8 brightness:0.8 alpha:1];
n.lineWidth = 4;
[routeMap addChild:n];
[self.pathArr addObject:path];
}
}
– (void)createTag
{
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointZero radius:10 startAngle:0 endAngle:2.0*M_PI clockwise:NO];
for (int i=0; i<4; i++) {
float x = (i%2) * 160 + 80;
float y = 120 – (i/2) * 80;
SKSpriteNode *tagCard = [SKSpriteNode spriteNodeWithColor:[SKColor colorWithHue:i*0.2 saturation:0.8 brightness:0.8 alpha:1] size:CGSizeMake(120, 40)];
tagCard.name = [NSString stringWithFormat:@”tag%d”, i];
tagCard.position = CGPointMake(x, y);
[self addChild:tagCard];
SKShapeNode *hole = [SKShapeNode node];
hole.position = CGPointMake(-40, 0);
hole.lineWidth = 4;
hole.path = path.CGPath;
[tagCard addChild:hole];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
SKNode *node = [self nodeAtPoint:p];
if ([node.name hasPrefix:@”tag”]) {
int idx = [[node.name substringFromIndex:node.name.length–1] intValue];
UIBezierPath *path = self.pathArr[idx];
SKColor *color = ((SKSpriteNode *)node).color;
SKSpriteNode *mark = [SKSpriteNode spriteNodeWithColor:color size:CGSizeMake(30, 30)];
SKNode *routeMap = [self childNodeWithName:@”routeMap”];
[routeMap addChild:mark];
[mark runAction:[SKAction sequence:@[[SKAction followPath:path.CGPath duration:3.0], [SKAction waitForDuration:1.0]]] completion:^{
[mark removeFromParent];
}];
}
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
SKView *spriteVeiw = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteVeiw];
SKScene *scene = [[RouteScene alloc] initWithSize:spriteVeiw.frame.size];
[spriteVeiw presentScene:scene];
}
@end