箱にボールをたくさん入れよう。というiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface BoxScene : SKScene
@end
@implementation BoxScene
– (void)didMoveToView:(SKView *)view
{
self.backgroundColor = [self color:4];
[self createWall];
[self createBox];
}
– (void)createWall
{
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
self.physicsBody.dynamic = NO;
}
– (void)createBox
{
float s = 60;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(s*0.3, s)];
[path addLineToPoint:CGPointMake(0, s)];
[path addLineToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(s, 0)];
[path addLineToPoint:CGPointMake(s, s)];
[path addLineToPoint:CGPointMake(s*0.7, s)];
for (int i=0; i<6; i++) {
float x = (i % 2) * 160 + 60;
float y = (i / 2) * 140 + 50;
SKShapeNode *box = [SKShapeNode node];
box.path = path.CGPath;
box.strokeColor = [self color:i%4];
box.lineWidth = 5;
box.fillColor = [[SKColor blackColor] colorWithAlphaComponent:0.9];
[self addChild:box];
box.position = CGPointMake(x, y);
box.physicsBody = [SKPhysicsBody bodyWithEdgeChainFromPath:path.CGPath];
}
}
– (void)createBall
{
SKSpriteNode *ball = [SKSpriteNode spriteNodeWithColor:[self color:arc4random()%4] size:CGSizeMake(10, 10)];
ball.position = CGPointMake(50, CGRectGetMaxY(self.frame) – 50);
[self addChild:ball];
ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:5];
ball.physicsBody.linearDamping = 0;
ball.physicsBody.restitution = 0.6;
int dx = arc4random() % 20;
[ball.physicsBody applyImpulse:CGVectorMake(dx, 0.1)];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self createBall];
}
#define ColorHex(rgbValue) [SKColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
– (UIColor*)color:(NSInteger)i
{
switch (i) {
case 0:
return ColorHex(0xF26835);
case 1:
return ColorHex(0x6AA6A6);
case 2:
return ColorHex(0xD9CCA7);
case 3:
return ColorHex(0xF2B263);
case 4:
return ColorHex(0x402B3C);
default:
break;
}
return 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 = [[BoxScene alloc] initWithSize:spriteView.frame.size];
[spriteView presentScene:scene];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end