九個のブロックを回転する箱の中でまぜまぜするiPhoneアプリのサンプルコードを描いてみます
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface NineScene : SKScene
@property (nonatomic) BOOL selected;
@end
@implementation NineScene
– (void)didMoveToView:(SKView *)view
{
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
[self createBox];
[self createColorBlocks];
[self createButton];
}
– (void)createBox
{
SKSpriteNode *box = [SKSpriteNode spriteNodeWithColor:[UIColor lightGrayColor] size:CGSizeMake(200, 200)];
box.name = @”box”;
box.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:box];
box.physicsBody = [SKPhysicsBody bodyWithBodies:@[
[SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(200, 10) center:CGPointMake(0, 100)],
[SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(200, 10) center:CGPointMake(0, –100)],
[SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(10, 200) center:CGPointMake(100, 0)],
[SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(10, 200) center:CGPointMake(-100, 0)],
]];
SKPhysicsJoint *pin = [SKPhysicsJointPin jointWithBodyA:self.physicsBody bodyB:box.physicsBody anchor:box.position];
[self.physicsWorld addJoint:pin];
}
– (void)createColorBlocks
{
CGPoint p = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
for (int i=0; i<9; i++) {
float x = (i % 3) * 60 + p.x – 60;
float y = (i / 3) * 60 + p.y – 60;
float hue = (i % 3) * 0.3;
SKSpriteNode *b = [SKSpriteNode spriteNodeWithColor:[SKColor colorWithHue:hue saturation:0.8 brightness:0.9 alpha:1] size:CGSizeMake(35, 35)];
b.position = CGPointMake(x, y);
[self addChild:b];
b.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(40, 40)];
}
}
– (void)createButton
{
SKSpriteNode *button = [SKSpriteNode spriteNodeWithColor:[SKColor whiteColor] size:CGSizeMake(120, 120)];
button.name = @”button”;
button.zRotation = M_PI * 0.25;
button.position = CGPointMake(CGRectGetMaxX(self.frame), 0);
[self addChild:button];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
SKNode *node = [self childNodeWithName:@”button”];
if ([node containsPoint:p]) {
self.selected = YES;
}
}
– (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
self.selected = NO;
}
– (void)update:(NSTimeInterval)currentTime
{
SKNode *box = [self childNodeWithName:@”box”];
if (self.selected) {
box.physicsBody.angularVelocity = 10.0;
} else {
box.physicsBody.angularVelocity = 0;
}
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[NineScene alloc] initWithSize:spriteView.frame.size];
[spriteView presentScene:scene];
}
@end