
ハノイの塔を試せるようなiPhoneアプリのサンプルコードを描いてみます。
動かすとこんな感じです
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface HanoiScene : SKScene
@property (nonatomic, weak) SKNode *selected;
@end
@implementation HanoiScene
– (void)didMoveToView:(SKView *)view
{
[self createSceneContents];
}
– (void)createSceneContents
{
[self createBar];
[self createRings];
}
– (void)createBar
{
SKSpriteNode *ground = [SKSpriteNode spriteNodeWithColor:[SKColor whiteColor] size:CGSizeMake(CGRectGetMaxX(self.frame), 20)];
ground.position = CGPointMake(CGRectGetMidX(self.frame), 10);
[self addChild:ground];
ground.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:ground.size];
ground.physicsBody.dynamic = NO;
for (int i=0; i<3; i++) {
float x = CGRectGetMaxX(self.frame) / 3.0 * (i + 0.5);
float y = 80;
SKSpriteNode *bar = [SKSpriteNode spriteNodeWithColor:[SKColor whiteColor] size:CGSizeMake(10, 160)];
bar.position = CGPointMake(x, y);
bar.zPosition = 1;
[self addChild:bar];
bar.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:bar.size];
bar.physicsBody.dynamic = NO;
}
}
– (void)createRings
{
for (int i=0; i<3; i++) {
SKColor *color = [SKColor colorWithHue:i * 0.3 saturation:0.8 brightness:1 alpha:1];
SKSpriteNode *ring = [SKSpriteNode spriteNodeWithColor:color size:CGSizeMake(100 – 30 * i, 30)];
ring.name = @”ring”;
ring.position = CGPointMake(CGRectGetMaxX(self.frame) / 6.0, 100 + i * 40);
ring.zPosition = 2;
[self addChild:ring];
CGSize size = CGSizeMake(ring.size.width / 2.0 – 10, 30);
SKPhysicsBody *left = [SKPhysicsBody bodyWithRectangleOfSize:size center:CGPointMake(-size.width/2.0 – 10, 0)];
SKPhysicsBody *right = [SKPhysicsBody bodyWithRectangleOfSize:size center:CGPointMake(size.width/2.0 + 10, 0)];
ring.physicsBody = [SKPhysicsBody bodyWithBodies:@[left, right]];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
[self enumerateChildNodesWithName:@”ring” usingBlock:^(SKNode *node, BOOL *stop) {
if ([node containsPoint:p]) {
node.physicsBody.affectedByGravity = NO;
self.selected = node;
}
}];
}
– (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (self.selected) {
CGPoint p = [[touches anyObject] locationInNode:self];
self.selected.position = p;
}
}
– (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
self.selected.physicsBody.affectedByGravity = YES;
self.selected = nil;
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidAppear:(BOOL)animated
{
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[HanoiScene alloc] initWithSize:spriteView.frame.size];
[spriteView presentScene:scene];
}
@end