
まるで囲んだ中に、小さい四角をたくさん入れます。重力の方向を指定することでこの小さな四角をシェイクして遊ぶiPhoneアプリを描いてみます。
動作イメージ
XcodeからiOS7 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface GravityScene : SKScene
@property BOOL contentCreated;
@property float lastUpdate;
@end
@implementation GravityScene
– (void)didMoveToView:(SKView *)view
{
if (!self.contentCreated) {
[self createSceneContents];
self.contentCreated = YES;
}
}
– (void)createSceneContents
{
SKShapeNode *circle = [[SKShapeNode alloc] init];
circle.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 100, 220, 220)].CGPath;
circle.lineWidth = 5;
circle.physicsBody = [SKPhysicsBody bodyWithEdgeChainFromPath:circle.path];
[self addChild:circle];
circle.name = @”circle”;
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(createStone:) userInfo:nil repeats:YES];
SKLabelNode *g = [SKLabelNode node];
g.text = @”G”;
g.position = CGPointMake(160, 50);
g.name = @”gravity”;
[self addChild:g];
}
– (void)createStone:(NSTimer*)sender
{
SKNode *circle = [self childNodeWithName:@”circle”];
SKSpriteNode *stone = [[SKSpriteNode alloc] initWithColor:[SKColor whiteColor] size:CGSizeMake(5, 5)];
stone.position = CGPointMake(150, 150);
[circle addChild:stone];
stone.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(5, 5)];
if ([[circle children] count] > 50) {
[sender invalidate];
}
}
– (void)update:(NSTimeInterval)currentTime
{
SKNode *gNode = [self childNodeWithName:@”gravity”];
self.physicsWorld.gravity = CGVectorMake((gNode.position.x – 160)/50.0, (gNode.position.y – 210)/50.0);
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
SKNode *gNode = [self childNodeWithName:@”gravity”];
gNode.position = p;
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[GravityScene alloc] initWithSize:self.view.bounds.size];
[spriteView presentScene:scene];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end