
机の足を消して、ボールを転がすiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface AshibaraiScene : SKScene
@end
@implementation AshibaraiScene
– (void)didMoveToView:(SKView *)view
{
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
[self createTable];
[self createApple];
}
– (void)createTable
{
for (int i=0; i<3; i++) {
float x = 170 * i + 70;
SKSpriteNode *tableTop = [SKSpriteNode spriteNodeWithColor:[SKColor brownColor] size:CGSizeMake(120, 10)];
tableTop.position = CGPointMake(x, 80);
[self addChild:tableTop];
tableTop.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:tableTop.size];
for (int j=0; j<2; j++) {
float lx = x – j * 90 + 45;
SKSpriteNode *leg = [SKSpriteNode spriteNodeWithColor:[SKColor brownColor] size:CGSizeMake(10, 70)];
leg.name = @”leg”;
leg.position = CGPointMake(lx, 40);
[self addChild:leg];
leg.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:leg.size];
}
}
}
– (void)createApple
{
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointZero radius:20 startAngle:0 endAngle:2.0*M_PI clockwise:NO];
for (int i=0; i<3; i++) {
SKShapeNode *apple = [SKShapeNode node];
apple.path = path.CGPath;
apple.position = CGPointMake(170 * i + 70, 110);
[self addChild:apple];
apple.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:path.CGPath];
apple.fillColor = [SKColor redColor];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
[self enumerateChildNodesWithName:@”leg” usingBlock:^(SKNode *node, BOOL *stop) {
if ([node containsPoint:p]) {
[node removeFromParent];
}
}];
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidAppear:(BOOL)animated
{
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[AshibaraiScene alloc] initWithSize:spriteView.bounds.size];
[spriteView presentScene:scene];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end