画面上にピンを並べます。上からブロックを落とします。ブロックがピンにあたるとはじかれてクルクル回転します。という感じのiPhoneアプリを描いてみます。
動作イメージ
XcodeからiOS7 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
#define UIColorHex(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
UIColor *hexColor(int i)
{
switch (i) {
case 0:
return UIColorHex(0x808080);
case 1:
return UIColorHex(0xFFFFFF);
case 2:
return UIColorHex(0xFF6E66);
case 3:
return UIColorHex(0x94FFF7);
case 4:
return UIColorHex(0xFFF78D);
default:
break;
}
return nil;
}
@interface SimpleScene : SKScene
@property BOOL contentCreated;
@end
@implementation SimpleScene
– (void)didMoveToView:(SKView *)view
{
if (!self.contentCreated) {
[self createSceneContents];
self.contentCreated = YES;
}
}
– (void)createSceneContents
{
self.backgroundColor = hexColor(0);
for (int i=0; i<16; i++) {
float x = (i % 4) * 80 + 40;
float y = (i / 4) * 120 + 60;
SKSpriteNode *pinNode = [self newPinNode];
pinNode.position = CGPointMake(x, y);
[self addChild:pinNode];
}
SKAction *makeBlock = [SKAction sequence:@[
[SKAction performSelector:@selector(addBlock) onTarget:self],
[SKAction waitForDuration:0.5 withRange:0.25]]];
[self runAction:[SKAction repeatActionForever:makeBlock]];
}
– (SKSpriteNode*)newPinNode
{
SKSpriteNode *node = [[SKSpriteNode alloc] initWithColor:hexColor(1) size:CGSizeMake(5, 5)];
node.name = @”pinNode”;
node.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:node.size];
node.physicsBody.dynamic = NO;
return node;
}
static inline CGFloat skRandf() {
return rand() / (CGFloat) RAND_MAX;
}
static inline CGFloat skRand(CGFloat low, CGFloat high) {
return skRandf() * (high – low);
}
– (void)addBlock
{
SKSpriteNode *block = [[SKSpriteNode alloc] initWithColor:hexColor(arc4random()%3+2) size:CGSizeMake(40, 40)];
block.position = CGPointMake(skRand(0, self.size.width), self.size.height – 50);
block.name = @”block”;
block.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:block.size];
block.physicsBody.usesPreciseCollisionDetection = YES;
[self addChild:block];
}
– (void)didSimulatePhysics
{
[self enumerateChildNodesWithName:@”block” usingBlock:^(SKNode *node, BOOL *stop) {
if (node.position.y < 0)
[node removeFromParent];
}];
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[SimpleScene alloc] initWithSize:CGSizeMake(320, 568)];
[spriteView presentScene:scene];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end