ウサギをシルクハットに入れると、ピョンピョンはねて出てくるといった感じで、iPhoneアプリのサンプルコードを描いてみます。
今回使った画像
動かすとこんな感じです
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface RabbitScene : SKScene
@property (nonatomic, weak) SKNode *selected;
@end
@implementation RabbitScene
– (void)didMoveToView:(SKView *)view
{
self.backgroundColor = [SKColor redColor];
[self createSceneContents];
}
– (void)createSceneContents
{
SKSpriteNode *hat = [SKSpriteNode spriteNodeWithImageNamed:@”hat”];
hat.position = CGPointMake(CGRectGetMidX(self.frame), hat.size.height/2.0);
hat.zPosition = 2;
[self addChild:hat];
SKSpriteNode *rabbit = [SKSpriteNode spriteNodeWithImageNamed:@”rabbit”];
rabbit.name = @”rabbit”;
rabbit.position = CGPointMake(CGRectGetMidX(self.frame), 150);
rabbit.zPosition = 1;
[self addChild:rabbit];
rabbit.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:rabbit.size];
rabbit.physicsBody.linearDamping = 1.0;
}
– (void)update:(NSTimeInterval)currentTime
{
SKNode *rabbit = [self childNodeWithName:@”rabbit”];
float rBottom = rabbit.frame.origin.y + rabbit.frame.size.height;
if (rBottom > 180 || self.selected) {
return;
}
// Hooke’s law
float k = 20.0;
float magicSpringForce = (180 – rBottom) * k;
[rabbit.physicsBody applyForce:CGVectorMake(0, magicSpringForce)];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
SKNode *rabbit = [self childNodeWithName:@”rabbit”];
if ([rabbit containsPoint:p]) {
self.selected = rabbit;
self.selected.physicsBody.affectedByGravity = NO;
}
}
– (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
self.selected.position = p;
}
– (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
self.selected.physicsBody.affectedByGravity = YES;
self.selected = nil;
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[RabbitScene alloc] initWithSize:spriteView.frame.size];
[spriteView presentScene:scene];
}
@end