iPhoneへびのおもちゃ

にょろにょろとうごかすヘビのおもちゃ、そんな感じのiPhoneアプリのサンプルコードを描いてみます。

使った画像


動かすとこんな感じです

サンプルコード

#import “ViewController.h”

#import <SpriteKit/SpriteKit.h>

@interface SnakeScene : SKScene

@property (nonatomic, weak) SKNode *selected;

@property CGPoint touchePoint;

@end

@implementation SnakeScene

– (void)didMoveToView:(SKView *)view

{

    [self createSceneContents];

}

– (void)createSceneContents

{

    self.backgroundColor = [SKColor brownColor];

    

    [self createFence];

    [self createSnake];

}

– (void)createFence

{

    UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.frame];

    SKShapeNode *fence = [SKShapeNode node];

    fence.lineWidth = 10;

    fence.path = path.CGPath;

    fence.strokeColor = [SKColor darkGrayColor];

    [self addChild:fence];

    

    fence.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromPath:path.CGPath];

}

– (void)createSnake

{

    SKNode *previous;

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

        float x = i * 50 + 100;

        NSString *imgName = (i==0) ? @”snakeHead” : @”snakeBody”;

        SKSpriteNode *snakeBody = [SKSpriteNode spriteNodeWithImageNamed:imgName];

        snakeBody.name = @”body”;

        snakeBody.position = CGPointMake(x, CGRectGetMidY(self.frame));

        [self addChild:snakeBody];

        

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

        

        if (previous) {

            SKPhysicsJointPin *pin = [SKPhysicsJointPin jointWithBodyA:previous.physicsBody bodyB:snakeBody.physicsBody anchor:CGPointMake(x –20, snakeBody.position.y)];

            [self.physicsWorld addJoint:pin];

        }

        previous = snakeBody;

    }

}

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

{

    CGPoint p = [[touches anyObject] locationInNode:self];

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

        if ([node containsPoint:p]) {

            self.selected = node;

        }

    }];

}

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

{

    self.touchePoint = [[touches anyObject] locationInNode:self];

}

– (void)update:(NSTimeInterval)currentTime

{

    if (self.selected) {

        float dx = self.touchePoint.xself.selected.position.x;

        float dy = self.touchePoint.yself.selected.position.y;

        CGVector v = CGVectorMake(3.0 * dx, 3.0 * dy);

        self.selected.physicsBody.velocity = v;

    }

}

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

{

    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 = [[SnakeScene alloc] initWithSize:spriteView.frame.size];

    [spriteView presentScene:scene];

}

@end