iPhoneうず

小さな四角をくるくる渦巻きという感じのiPhoneアプリのサンプルコードを描いてみます。

動かすとこんな感じです

サンプルコード

#import “ViewController.h”

#import <SpriteKit/SpriteKit.h>

@interface WhirlpoolsScene : SKScene

@end

@implementation WhirlpoolsScene

– (void)didMoveToView:(SKView *)view

{

    [self createSceneContents];

}

– (void)createSceneContents

{

    self.physicsWorld.gravity = CGVectorMake(0, 0);

    self.backgroundColor = [SKColor colorWithRed:0.8 green:0.8 blue:1.0 alpha:1];

    [self createChips];

}

– (void)createChips

{

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

        float x = (arc4random() % 300) + 10;

        float y = (arc4random() % 300) + 100;

        SKColor *color = [SKColor colorWithHue:0.1 + (arc4random() % 9) * 0.1 saturation:0.8 brightness:1.0 alpha:1.0];

        SKSpriteNode *chip = [SKSpriteNode spriteNodeWithColor:color size:CGSizeMake(20, 20)];

        chip.name = @”chip”;

        chip.position = CGPointMake(x, y);

        [self addChild:chip];

        

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

        chip.physicsBody.friction = 1.0;

    }

}

– (void)update:(NSTimeInterval)currentTime

{

    CGPoint o = CGPointMake(160, 250);

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

        CGVector v = CGVectorMake(node.position.x – o.x, node.position.y – o.y);

        float acc = 1.0 + (arc4random() % 10) * 0.4;

        node.physicsBody.velocity = CGVectorMake(v.dy * acc, -v.dx * acc);

    }];

}

– (void)didSimulatePhysics

{

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

        if (node.position.x < –50 || node.position.x > 400) {

            [node removeFromParent];

        }

    }];

}

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

{

    [self createChips];

}

@end

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidAppear:(BOOL)animated

{

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

    [self.view addSubview:spriteView];

    

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

    [spriteView presentScene:scene];

}

@end