iPhone 頭ジャンプ

頭から地面の隙間にジャンプして遊ぶiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

#import <SpriteKit/SpriteKit.h>

@interface JumpScene : SKScene

@end

@implementation JumpScene

– (void)didMoveToView:(SKView *)view

{

    self.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];

    

    [self createGround];

    [self createJumper];

}

– (void)createGround

{

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

        float x = 30 * i;

        SKSpriteNode *g = [SKSpriteNode spriteNodeWithColor:[SKColor brownColor] size:CGSizeMake(20, 40)];

        g.position = CGPointMake(x, 30 – i *0.5);

        [self addChild:g];

        

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

        g.physicsBody.dynamic = NO;

    }

}

– (void)createJumper

{

    SKSpriteNode *jumper = [SKSpriteNode spriteNodeWithImageNamed:@”bar”];

    jumper.position = CGPointMake(50, 80);

    jumper.size = CGSizeMake(40, 80);

    jumper.name = @”jumper”;

    [self addChild:jumper];

    

    jumper.physicsBody = [SKPhysicsBody bodyWithBodies:@[[SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(5, jumper.size.height)], [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(40, 10) center:CGPointMake(0, -jumper.size.height/2.0 + 5)], [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(40, 10) center:CGPointMake(0, 20)]]];

    

    jumper.physicsBody.allowsRotation = NO;

}

– (void)update:(NSTimeInterval)currentTime

{

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

    jumper.physicsBody.velocity = CGVectorMake(30.0, 0);

}

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

{

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

    jumper.name = @”jumped”;

    jumper.physicsBody.allowsRotation = YES;

    [jumper.physicsBody applyImpulse:CGVectorMake(10, 25)];

    [jumper.physicsBody applyAngularImpulse:0.01];

    

    [self performSelector:@selector(createJumper) withObject:nil afterDelay:1.0];

}

@end

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidAppear:(BOOL)animated

{

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

    [self.view addSubview:spriteView];

    

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

    [spriteView presentScene:scene];

}

@end