ボールとピンだけで作ったカンタンなピンボールゲームをiPhoneアプリとして描いてみます。(SpriteKitをつかっています。)
動作イメージ
XcodeからiOS7 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface Machine : SKScene
@property BOOL contentCreated;
@end
@implementation Machine
– (void)didMoveToView:(SKView *)view
{
if (!self.contentCreated) {
[self createSceneContents];
self.contentCreated = YES;
}
}
– (void)createSceneContents
{
self.backgroundColor = [SKColor greenColor];
UIBezierPath *path = [UIBezierPath bezierPath];
[path addArcWithCenter:CGPointMake(0, 0) radius:5 startAngle:0 endAngle:2*M_PI clockwise:NO];
for (int i=0; i<15; i++) {
float x = (i % 3) * 80 + 30 + arc4random() % 30;
float y = (i / 3) * 70 + 50 + arc4random() % 40;
SKShapeNode *node = [[SKShapeNode alloc] init];
node.path = path.CGPath;
node.position = CGPointMake(x, y);
node.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:5];
node.physicsBody.dynamic = NO;
node.strokeColor = [SKColor lightGrayColor];
node.fillColor = [SKColor lightGrayColor];
[self addChild:node];
}
SKNode *ball = [self createBall];
path = [UIBezierPath bezierPath];
[path addArcWithCenter:ball.position radius:30 startAngle:0 endAngle:M_PI clockwise:NO];
SKShapeNode *guideLineA = [[SKShapeNode alloc] init];
guideLineA.path = path.CGPath;
guideLineA.physicsBody = [SKPhysicsBody bodyWithEdgeChainFromPath:path.CGPath];
guideLineA.physicsBody.dynamic = NO;
[self addChild:guideLineA];
}
– (SKNode*)createBall
{
UIBezierPath *path = [UIBezierPath bezierPath];
[path addArcWithCenter:CGPointMake(0, 0) radius:10 startAngle:0 endAngle:2*M_PI clockwise:NO];
SKShapeNode *ball = [[SKShapeNode alloc] init];
ball.path = path.CGPath;
ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:10];
ball.position = CGPointMake(280, 40);
ball.fillColor = [SKColor whiteColor];
ball.strokeColor = [SKColor whiteColor];
ball.name = @”ball”;
[self addChild:ball];
return ball;
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
SKNode *ball = [self childNodeWithName:@”ball”];
float vx = (arc4random() % 10) / 10.0 + 1.0;
[ball.physicsBody applyImpulse:CGVectorMake(-vx, 16)];
}
– (void)didSimulatePhysics
{
SKNode *ball = [self childNodeWithName:@”ball”];
if (ball.position.y < 0) {
[ball removeFromParent];
[self createBall];
}
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *machine = [[Machine alloc] initWithSize:CGSizeMake(320, 568)];
[spriteView presentScene:machine];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end