
江ノ島水族館に行ってきたので、今日はクラゲがふよふよするようなiPhoneアプリのサンプルコードを描いてみます。
動作イメージ
XcodeからiOS7 iPhone Simulatorで動かすとこんな感じになります
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface JellyfishScene : SKScene
@end
@implementation JellyfishScene
– (void)didMoveToView:(SKView *)view
{
self.physicsWorld.gravity = CGVectorMake(0, –0.2);
self.backgroundColor = [SKColor colorWithRed:0.9 green:0.9 blue:1.0 alpha:1.0];
[self createJellyFish];
}
– (void)createJellyFish
{
SKSpriteNode *head = [SKSpriteNode spriteNodeWithImageNamed:@”jellyfish_head”];
head.name = @”head”;
[self addChild:head];
head.position = CGPointMake(150, 250);
head.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:head.size];
[self addWireToBody:head AtPoint:CGPointMake(190, 220)];
[self addWireToBody:head AtPoint:CGPointMake(170, 220)];
[self addWireToBody:head AtPoint:CGPointMake(150, 220)];
[self addWireToBody:head AtPoint:CGPointMake(130, 220)];
[self addWireToBody:head AtPoint:CGPointMake(110, 220)];
}
#define SPACE_BETWEEN_SEGMENTS 7
– (void)addWireToBody:(SKNode*)body AtPoint:(CGPoint)p
{
SKNode *previous;
for (int i=0; i<10; i++) {
float x = p.x;
float y = p.y – (SPACE_BETWEEN_SEGMENTS + 1) * i;
SKTexture *texture = [SKTexture textureWithImageNamed:@”jellyfish_hand”];
SKSpriteNode *node = [SKSpriteNode spriteNodeWithTexture:texture size:CGSizeMake(2, SPACE_BETWEEN_SEGMENTS)];
node.position = CGPointMake(x, y);
node.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:node.size];
[self addChild:node];
if (i == 0) {
SKPhysicsJointPin *joint = [SKPhysicsJointPin jointWithBodyA:node.physicsBody bodyB:body.physicsBody anchor:p];
[self.physicsWorld addJoint:joint];
} else {
SKPhysicsJointPin *joint = [SKPhysicsJointPin jointWithBodyA:node.physicsBody bodyB:previous.physicsBody anchor:CGPointMake(x, y+SPACE_BETWEEN_SEGMENTS/2)];
[self.physicsWorld addJoint:joint];
}
previous = node;
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
SKNode *jellyfish = [self childNodeWithName:@”head”];
[jellyfish.physicsBody applyImpulse:CGVectorMake(0.5, 10.1)];
}
– (void)didSimulatePhysics
{
SKNode *jellyfish = [self childNodeWithName:@”head”];
if (jellyfish.position.y < –50) {
[jellyfish removeFromParent];
[self createJellyFish];
}
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
JellyfishScene *scene = [[JellyfishScene alloc] initWithSize:spriteView.frame.size];
[spriteView presentScene:scene];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end