ボールが階段をぴょんぴょん跳ねて上っていく感じにiPhoneゲームのサンプルコードを描いてみます。
今回使った画像
サンプルを動かすとこんな感じです
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface StairScene : SKScene
@property BOOL contentCreated;
@end
@implementation StairScene
– (void)didMoveToView:(SKView *)view
{
if (!self.contentCreated) {
[self createSceneContents];
self.contentCreated = YES;
}
}
– (void)createSceneContents
{
[self createStair];
}
– (void)createBallAtPoint:(CGPoint)p
{
SKSpriteNode *ball = [SKSpriteNode spriteNodeWithImageNamed:@”ball”];
ball.name = @”ball”;
ball.size = CGSizeMake(50, 50);
ball.position = p;
[self addChild:ball];
ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:ball.size.width/2.0];
ball.physicsBody.restitution = 1.0;
}
– (void)createStair
{
for (int i=0; i<5; i++) {
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(0, 50)];
[path addLineToPoint:CGPointMake(100, 40)];
SKShapeNode *node = [SKShapeNode node];
node.strokeColor = [SKColor whiteColor];
node.lineWidth = 3;
node.path = path.CGPath;
[self addChild:node];
float x = i * 100;
float y = i * 38;
node.position = CGPointMake(x, y);
[path addLineToPoint:CGPointMake(80, 0)];
[path closePath];
node.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:path.CGPath];
node.physicsBody.dynamic = NO;
}
}
– (void)didSimulatePhysics
{
SKNode *node = [self childNodeWithName:@”ball”];
if (!CGRectContainsPoint(self.frame, node.position)) {
[node removeFromParent];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
[self createBallAtPoint:p];
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
}
– (void)viewDidAppear:(BOOL)animated
{
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[StairScene alloc] initWithSize:spriteView.frame.size];
[spriteView presentScene:scene];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end