
数が書いてある箱にボールを入れるiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@import SpriteKit;
@interface PinScene : SKScene
@end
@implementation PinScene
– (void)didMoveToView:(SKView *)view
{
self.backgroundColor = [SKColor lightGrayColor];
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
self.physicsWorld.speed = 0.5;
[self createPin];
[self createPocket];
[self createBall];
[self createButton];
}
– (void)createPin
{
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointZero radius:5 startAngle:0 endAngle:2.0*M_PI clockwise:NO];
for (int i=0; i<6; i++) {
SKShapeNode *pin = [SKShapeNode node];
pin.position = CGPointMake((i%3) * 90 + 45 + (i/3) * 45, (i/3) * 80 + 200);
pin.path = path.CGPath;
[self addChild:pin];
pin.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:5];
pin.physicsBody.dynamic = NO;
}
}
– (void)createPocket
{
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(-40, 40)];
[path addLineToPoint:CGPointMake(-40, –40)];
[path addLineToPoint:CGPointMake(40, –40)];
[path addLineToPoint:CGPointMake(40, 40)];
for (int i=0; i<3; i++) {
SKShapeNode *pocket = [SKShapeNode node];
pocket.path = path.CGPath;
pocket.position = CGPointMake(i * 100 + 60, 80);
[self addChild:pocket];
SKLabelNode *number = [SKLabelNode node];
number.text = [NSString stringWithFormat:@”%d”, i+1];
[pocket addChild:number];
pocket.physicsBody = [SKPhysicsBody bodyWithEdgeChainFromPath:path.CGPath];
}
}
– (void)createBall
{
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointZero radius:15 startAngle:0 endAngle:2*M_PI clockwise:NO];
for (int i=0; i<6; i++) {
SKShapeNode *ball = [SKShapeNode node];
ball.name = @”ball”;
ball.path = path.CGPath;
ball.fillColor = [SKColor colorWithHue:i * 0.14 saturation:0.8 brightness:1 alpha:0.7];
ball.position = CGPointMake(i * 50 + 30, 440);
[self addChild:ball];
ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:15];
ball.physicsBody.restitution = 0.6;
ball.physicsBody.dynamic = NO;
}
}
– (void)createButton
{
SKLabelNode *btn = [SKLabelNode node];
btn.name = @”button”;
btn.text = @”[start]”;
btn.position = CGPointMake(160, 380);
[self addChild:btn];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
SKNode *btn = [self childNodeWithName:@”button”];
if ([btn containsPoint:p]) {
[self enumerateChildNodesWithName:@”ball” usingBlock:^(SKNode *node, BOOL *stop) {
node.physicsBody.dynamic = YES;
[node.physicsBody applyImpulse:CGVectorMake(arc4random() % 10, arc4random() % 10)];
}];
}
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[PinScene alloc] initWithSize:spriteView.frame.size];
[spriteView presentScene:scene];
}
@end