iPhone木馬

ゆらゆら揺れるだけの木馬みたいな感じで、iPhoneアプリのサンプルコードを描いてみます。

今回使った画像


動かすとこんな感じです

サンプルコード

#import “ViewController.h”

#import <SpriteKit/SpriteKit.h>

typedef enum : int8_t

{

    TypeWoodHorse = 0x1 << 1,

    TypeArchElement = 0x1 << 2,

    TypeGround = 0x1 << 3,

} ColliderType;

@interface WoodScene : SKScene

@end

@implementation WoodScene

– (void)didMoveToView:(SKView *)view

{

    [self createSceneContents];

}

– (void)createSceneContents

{

    self.backgroundColor = [SKColor brownColor];

    

    [self createGround];

    [self createWoodHorse];

}

– (void)createGround

{

    SKSpriteNode *ground = [SKSpriteNode spriteNodeWithColor:[SKColor grayColor] size:CGSizeMake(CGRectGetMaxX(self.frame), 50)];

    ground.position = CGPointMake(CGRectGetMidX(self.frame), 50);

    [self addChild:ground];

    

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

    ground.physicsBody.dynamic = NO;

    ground.physicsBody.categoryBitMask = TypeGround;

    ground.physicsBody.collisionBitMask = TypeArchElement;

}

– (void)createWoodHorse

{

    SKSpriteNode *woodHourse = [SKSpriteNode spriteNodeWithImageNamed:@”woodhorse”];

    woodHourse.position = CGPointMake(CGRectGetMidX(self.frame), 200);

    [self addChild:woodHourse];

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

    woodHourse.physicsBody.categoryBitMask = TypeWoodHorse;

    woodHourse.physicsBody.collisionBitMask = TypeWoodHorse; // no collision

    

    // create arch

    CGPoint o = CGPointMake(woodHourse.position.x, woodHourse.position.y + 100);

    float r = 170;

    for (int angle=235; angle<310; angle += 10) {

        float x = r * cos(angle * M_PI/180.0) + o.x;

        float y = r * sin(angle * M_PI/180.0) + o.y;

        SKSpriteNode *dot = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(4, 4)];

        dot.position = CGPointMake(x, y);

        [self addChild:dot];

        dot.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:2];

        dot.physicsBody.categoryBitMask = TypeArchElement;

        dot.physicsBody.collisionBitMask = TypeGround;

        

        SKPhysicsJointFixed *fixed = [SKPhysicsJointFixed jointWithBodyA:woodHourse.physicsBody bodyB:dot.physicsBody anchor:dot.position];

        [self.physicsWorld addJoint:fixed];

    }

}

@end

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    

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

    [self.view addSubview:spriteView];

    

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

    [spriteView presentScene:scene];

}

@end