
画面をタッチすると、ヘリコプターが垂直上昇!といったかんじのiPhoneアプリを描いてみます。
動作イメージ
XcodeからiOS7 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface LandScene : SKScene
@property BOOL contentCreated;
@property BOOL accel;
@property float speed;
@end
@implementation LandScene
– (void)didMoveToView:(SKView *)view
{
if (!self.contentCreated) {
[self createSceneContents];
[self addGesture];
self.contentCreated = YES;
self.speed = 0.01;
}
}
– (void)createSceneContents
{
self.backgroundColor = [UIColor blueColor];
SKSpriteNode *ground = [SKSpriteNode spriteNodeWithColor:[SKColor brownColor] size:CGSizeMake(320, 20)];
ground.position = CGPointMake(160, 100);
ground.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:ground.size];
ground.physicsBody.dynamic = NO;
[self addChild:ground];
SKNode *helicopter = [SKNode node];
helicopter.name = @”helicopter”;
[self addChild:helicopter];
helicopter.position = CGPointMake(200, 200);
helicopter.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(100, 80)];
SKSpriteNode *body = [SKSpriteNode spriteNodeWithImageNamed:@”body”];
[helicopter addChild:body];
SKSpriteNode *rotorBig = [SKSpriteNode spriteNodeWithImageNamed:@”rotorBig”];
rotorBig.name = @”rotor”;
rotorBig.position = CGPointMake(-20, 50);
[helicopter addChild:rotorBig];
SKSpriteNode *rotorSmall = [SKSpriteNode spriteNodeWithImageNamed:@”rotorSmall”];
rotorSmall.position = CGPointMake(80, 30);
[helicopter addChild:rotorSmall];
SKAction *rotation = [SKAction rotateByAngle:M_PI * 2.0 duration:1.0];
[rotorSmall runAction:[SKAction repeatActionForever:rotation]];
}
– (void)addGesture
{
UILongPressGestureRecognizer *lpg = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(push:)];
[self.view addGestureRecognizer:lpg];
}
– (void)push:(UILongPressGestureRecognizer*)gr
{
if (gr.state == UIGestureRecognizerStateBegan) {
self.accel = YES;
} else if (gr.state == UIGestureRecognizerStateEnded) {
self.accel = NO;
}
}
– (void)update:(NSTimeInterval)currentTime
{
SKNode *rotor = [self childNodeWithName:@”//rotor”];
if (self.accel) {
self.speed = self.speed * 1.10;
} else {
if (self.speed > 0.01) {
self.speed = self.speed / 1.05;
}
}
rotor.zRotation += self.speed;
SKNode *helicopter = [self childNodeWithName:@”helicopter”];
helicopter.physicsBody.velocity = CGVectorMake(0, self.speed);
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[LandScene alloc] initWithSize:spriteView.bounds.size];
[spriteView presentScene:scene];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end