
穴を掘ったところに、水玉がポタポタながれていくようなiPhoneアプリを描いてみます。
動作イメージ
XcodeからiOS7 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
#define ColorHex(rgbValue) [SKColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
@interface DigScene : SKScene
@property BOOL contentCreated;
@end
@implementation DigScene
– (void)didMoveToView:(SKView *)view
{
if (!self.contentCreated) {
[self createSceneContents];
self.contentCreated = YES;
}
}
– (void)createSceneContents
{
self.backgroundColor = ColorHex(0x6F3816);
[self createWater];
[self createGround];
}
– (void)createWater
{
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(-5, –5, 10, 10)];
for (int i=0; i<16; i++) {
float x = (i % 32) * 20;
float y = 400;
SKShapeNode *node = [SKShapeNode node];
node.name = @”drop”;
node.fillColor = ColorHex(0x44E0FF);
node.strokeColor = node.fillColor;
node.position = CGPointMake(x, y);
node.path = path.CGPath;
node.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:5];
[self addChild:node];
}
}
– (void)createGround
{
for (int i=0; i<480; i++) {
float x = (i % 32) * 20 + 10;
float y = (i / 32) * 20;
SKSpriteNode *node = [SKSpriteNode spriteNodeWithColor:ColorHex(0x80522D) size:CGSizeMake(20, 20)];
node.position = CGPointMake(x, y);
node.name = @”ground”;
[self addChild:node];
node.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:node.size];
node.physicsBody.dynamic = NO;
}
}
– (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
CGRect checkFrame = CGRectMake(p.x – 10, p.y – 10, 20, 20);
[self enumerateChildNodesWithName:@”ground” usingBlock:^(SKNode *node, BOOL *stop) {
if (CGRectContainsPoint(checkFrame, node.position)) {
[node removeFromParent];
}
}];
}
– (void)update:(NSTimeInterval)currentTime
{
[self enumerateChildNodesWithName:@”drop” usingBlock:^(SKNode *node, BOOL *stop) {
if (node.position.x < 160) {
node.physicsBody.angularVelocity = –5;
} else {
node.physicsBody.angularVelocity = 5;
}
}];
}
– (void)didSimulatePhysics
{
// restart
if (![self childNodeWithName:@”drop”]) {
[self createWater];
}
// remove
[self enumerateChildNodesWithName:@”drop” 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.frame];
[self.view addSubview:spriteView];
SKScene *scene = [[DigScene alloc] initWithSize:self.view.bounds.size];
[spriteView presentScene:scene];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end