ダイアルで重力の方向を操作するiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface GravityScene : SKScene
@end
@implementation GravityScene
– (void)didMoveToView:(SKView *)view
{
// self.physicsWorld.speed = 0.5;
[self createWall];
[self createDoor];
[self createDial];
[self createChips];
}
– (void)createWall
{
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
self.physicsBody.dynamic = NO;
}
– (void)createDoor
{
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.frame];
[path appendPath:[UIBezierPath bezierPathWithArcCenter:CGPointMake(160, 250) radius:140 startAngle:0 endAngle:2*M_PI clockwise:NO]];
path.usesEvenOddFillRule = YES;
SKShapeNode *door = [SKShapeNode node];
door.path = path.CGPath;
door.fillColor = [SKColor lightGrayColor];
door.zPosition = 1;
[self addChild:door];
}
– (void)createDial
{
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(-40, –40, 80, 80)];
SKShapeNode *dial = [SKShapeNode node];
dial.name = @”dial”;
dial.path = path.CGPath;
dial.position = CGPointMake(270, 50);
dial.lineWidth = 5;
dial.strokeColor = [SKColor redColor];
dial.zPosition = 2;
[self addChild:dial];
SKLabelNode *arrow = [SKLabelNode node];
arrow.text = @”↓”;
arrow.fontColor = [SKColor redColor];
arrow.verticalAlignmentMode = SKLabelVerticalAlignmentModeCenter;
arrow.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeCenter;
[dial addChild:arrow];
}
– (void)createChips
{
for (int i=0; i<100; i++) {
float x = (i % 10) * 30 + arc4random() % 5;
float y = (i / 10) * 30;
SKSpriteNode *node = [SKSpriteNode spriteNodeWithColor:[SKColor colorWithHue:i*0.01 saturation:0.7 brightness:0.9 alpha:1.0] size:CGSizeMake(5, 5)];
node.position = CGPointMake(x, y);
[self addChild:node];
node.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:node.size];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
SKNode *dial = [self childNodeWithName:@”dial”];
if ([dial containsPoint:p]) {
float dx = p.x – dial.position.x;
float dy = p.y – dial.position.y;
float angle = atan2f(dx, -dy);
[dial runAction:[SKAction rotateToAngle:angle duration:0.2]];
angle -= M_PI_2;
self.physicsWorld.gravity = CGVectorMake(cos(angle), sin(angle));
}
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[GravityScene alloc] initWithSize:spriteView.frame.size];
[spriteView presentScene:scene];
}
@end