iPhoneドミノ

一列にドミノをならべて倒す!といったかんじのiPhoneアプリを描いてみます。

動作イメージ
XcodeからiOS7 iPhone Simulatorで動かすとこんな感じになります。

サンプルコード

#import “ViewController.h”

#import <SpriteKit/SpriteKit.h>

@interface DominoScene : SKScene

@property BOOL contentCreated;

@end

@implementation DominoScene

– (void)didMoveToView:(SKView *)view

{

    if (!self.contentCreated) {

        [self createSceneContents];

        self.contentCreated = YES;

    }

}

– (void)createSceneContents

{

    SKSpriteNode *ground = [SKSpriteNode spriteNodeWithColor:[SKColor brownColor] size:CGSizeMake(568, 10)];

    ground.position = CGPointMake(284, 15);

    ground.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:ground.size];

    ground.physicsBody.dynamic = NO;

    [self addChild:ground];

    

    [self createDomino];

}

– (void)createDomino

{

    for (int i=0; i<12; i++) {

        float x = i * 30 + 80;

        SKSpriteNode *domino = [SKSpriteNode spriteNodeWithColor:[SKColor greenColor] size:CGSizeMake(10, 50)];

        domino.name = @”domino”;

        domino.position = CGPointMake(x, 50);

        domino.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:domino.size];

        [self addChild:domino];

    }

}

– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    SKNode *firstDomino = [self childNodeWithName:@”domino”];

    [firstDomino.physicsBody applyImpulse:CGVectorMake(1, 0) atPoint:CGPointMake(0, 50)];

    

    [self performSelector:@selector(restart) withObject:nil afterDelay:3.0];

}

– (void)restart

{

    [self enumerateChildNodesWithName:@”domino” usingBlock:^(SKNode *node, BOOL *stop) {

        [node removeFromParent];

    }];

    

    [self createDomino];

}

@end

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    

    SKView *spriteView = [[SKView alloc] initWithFrame:CGRectMake(0, 0, 568, 320)];

    [self.view addSubview:spriteView];

    

    SKScene *scene = [[DominoScene alloc] initWithSize:spriteView.frame.size];

    [spriteView presentScene:scene];

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end