iPhoneシェイク丸

短冊切りにした丸を上下にシェイクするiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@import SpriteKit;

@interface ShakeScene : SKScene

@end

@implementation ShakeScene

– (void)didMoveToView:(SKView *)view

{

    self.backgroundColor = [SKColor colorWithWhite:0.6 alpha:1];

    self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];

    [self createBar];

}

– (void)createBar

{

    float r = 140;

    CGPoint o = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));

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

        float x = i * 10 – r;

        float h = sqrtf(powf(r, 2) – powf(x, 2));

        SKSpriteNode *bar = [SKSpriteNode spriteNodeWithColor:[SKColor purpleColor] size:CGSizeMake(9, r * 2.0)];

        bar.name = @”bar”;

        bar.position = CGPointMake(x + o.x, o.y);

        [self addChild:bar];

        

        SKSpriteNode *yellow = [SKSpriteNode spriteNodeWithColor:[SKColor yellowColor] size:CGSizeMake(8, h * 2.0)];

        [bar addChild:yellow];

        

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

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

            SKPhysicsJointSpring *spring = [SKPhysicsJointSpring jointWithBodyA:bar.physicsBody bodyB:self.physicsBody anchorA:bar.position anchorB:CGPointMake(bar.position.x, bar.position.y + (i==0 ? 200 : –200))];

            spring.frequency = 0.8;

            spring.damping = 0.3;

            [self.physicsWorld addJoint:spring];

        }

    }

}

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

{

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

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

        if ([node containsPoint:p]) {

            [node.physicsBody applyImpulse:CGVectorMake(0, 20)];

        }

    }];

}

@end

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];

    [self.view addSubview:spriteView];

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

    [spriteView presentScene:scene];

}

@end