トランポリンのボヨンに合わせて高くジャンプしよう。なiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface TrampolineScene : SKScene
@end
@implementation TrampolineScene
– (void)didMoveToView:(SKView *)view
{
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
self.backgroundColor = [SKColor colorWithWhite:0.94 alpha:1];
[self createTrampoline];
[self createJumper];
[self createLines];
}
– (void)createTrampoline
{
for (int i=0; i<2; i++) {
SKSpriteNode *leg = [SKSpriteNode spriteNodeWithColor:[SKColor lightGrayColor] size:CGSizeMake(10, 30)];
leg.position = CGPointMake(150 + i * 200, 15);
[self addChild:leg];
leg.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:leg.size];
leg.physicsBody.dynamic = NO;
}
SKNode *tmp = nil;
for (int i=0; i<10; i++) {
SKSpriteNode *m = [SKSpriteNode spriteNodeWithColor:[SKColor orangeColor] size:CGSizeMake(18, 5)];
m.position = CGPointMake(i * 20 + 160, 30);
[self addChild:m];
m.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:m.size];
if (tmp) {
CGPoint pa = CGPointMake(m.position.x – 8, m.position.y);
CGPoint pb = CGPointMake(tmp.position.x + 8, tmp.position.y);
SKPhysicsJointSpring *s = [SKPhysicsJointSpring jointWithBodyA:m.physicsBody bodyB:tmp.physicsBody anchorA:pa anchorB:pb];
s.frequency = 3000;
[self.physicsWorld addJoint:s];
}
tmp = m;
if (i==0 || i==9) {
SKPhysicsJointPin *pin = [SKPhysicsJointPin jointWithBodyA:m.physicsBody bodyB:self.physicsBody anchor:CGPointMake(m.position.x, m.position.y)];
[self.physicsWorld addJoint:pin];
}
}
}
– (void)createJumper
{
SKSpriteNode *h = [SKSpriteNode spriteNodeWithColor:[SKColor purpleColor] size:CGSizeMake(30, 30)];
h.name = @”jumper”;
h.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame)- 50);
[self addChild:h];
h.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:h.size];
}
– (void)createLines
{
for (int i=0; i<4; i++) {
SKSpriteNode *line = [SKSpriteNode spriteNodeWithColor:[SKColor colorWithWhite:0.8 alpha:1] size:CGSizeMake(CGRectGetMaxX(self.frame), 2)];
line.position = CGPointMake(CGRectGetMidX(self.frame), i * 50 + 100);
[self addChild:line];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
SKNode *jumper = [self childNodeWithName:@”jumper”];
[jumper.physicsBody applyImpulse:CGVectorMake(0, 15)];
}
– (void)update:(NSTimeInterval)currentTime
{
SKNode *jumper = [self childNodeWithName:@”jumper”];
jumper.physicsBody.velocity = CGVectorMake(0, jumper.physicsBody.velocity.dy);
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[TrampolineScene alloc] initWithSize:spriteView.frame.size];
[spriteView presentScene:scene];
}
@end