iPhoneサイクロイド

丸をころがしてサイクロイドなiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@import SpriteKit;

@interface Cycloid : SKScene

@end

@implementation Cycloid

– (void)didMoveToView:(SKView *)view

{

    self.physicsWorld.speed = 0;

    [self createGround];

    [self createCircle];

}

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

{

    self.physicsWorld.speed = 1.0;

}

– (void)createGround

{

    float w = CGRectGetMaxX(self.frame);

    float h = CGRectGetMaxY(self.frame) / 4.0;

    SKSpriteNode *ground = [SKSpriteNode spriteNodeWithColor:[SKColor whiteColor] size:CGSizeMake(w, h)];

    ground.position = CGPointMake(CGRectGetMidX(self.frame), h/2.0);

    ground.zRotation = –0.1;

    [self addChild:ground];

    

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

    ground.physicsBody.dynamic = NO;

}

– (void)createCircle

{

    float r = arc4random() % 40 + 20;

    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointZero radius:r startAngle:0 endAngle:2.0*M_PI clockwise:NO];

    SKShapeNode *circle = [SKShapeNode node];

    circle.name = @”circle”;

    circle.path = path.CGPath;

    circle.position = CGPointMake(r, 200);

    circle.fillColor = [SKColor whiteColor];

    [self addChild:circle];

    circle.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:r];

    

    SKColor *color = [SKColor colorWithHue:(arc4random() % 5) * 0.2 saturation:0.9 brightness:1 alpha:1];

    SKSpriteNode *mark = [SKSpriteNode spriteNodeWithColor:color size:CGSizeMake(r*0.2, r*0.2)];

    mark.name = @”mark”;

    mark.position = CGPointMake(0, r*0.8);

    [circle addChild:mark];

}

– (void)update:(NSTimeInterval)currentTime

{

    SKNode *circle = [self childNodeWithName:@”circle”];

    if (circle) {

        

        SKSpriteNode *mark = (SKSpriteNode *)[circle childNodeWithName:@”mark”];

        SKSpriteNode *dot = [SKSpriteNode spriteNodeWithColor:mark.color size:mark.size];

        dot.position = [circle convertPoint:mark.position toNode:self];

        [self addChild:dot];

        

        if (circle.position.x > CGRectGetMaxX(self.frame)) {

            [circle removeFromParent];

            [self createCircle];

        }

    }

}

@end

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidAppear:(BOOL)animated

{

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

    [self.view addSubview:spriteView];

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

    [spriteView presentScene:scene];

}

@end