円周率の数字を画面の中心を軸にしてクルクル回すiPhoneアプリのサンプルコードを描いてみます。
動かすとこんな感じです
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface SpinScene : SKScene
@property int count;
@end
@implementation SpinScene
– (void)didMoveToView:(SKView *)view
{
[self createSceneContents];
}
– (void)createSceneContents
{
self.backgroundColor = [self color:4];
self.physicsWorld.gravity = CGVectorMake(0, 0);
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
for (int i=0; i<14; i++) {
double delayInSeconds = 0.6 * i;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self createText];
});
}
}
– (void)createText
{
SKLabelNode *l = [SKLabelNode node];
l.name = @”spinText”;
l.text = [[@(M_PI) stringValue] substringWithRange:NSMakeRange(self.count, 1)];
l.fontColor = [self color:arc4random()%4];
self.count++;
l.position = CGPointMake(CGRectGetMidX(self.frame) + 130, CGRectGetMidY(self.frame));
[self addChild:l];
l.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:l.fontSize*0.5];
l.physicsBody.linearDamping = 0;
l.physicsBody.angularDamping = 0;
[l.physicsBody applyImpulse:CGVectorMake(0, 3)];
}
– (void)update:(NSTimeInterval)currentTime
{
// add force to center
[self enumerateChildNodesWithName:@”spinText” usingBlock:^(SKNode *node, BOOL *stop) {
float dx = CGRectGetMidX(self.frame) – node.position.x;
float dy = CGRectGetMidY(self.frame) – node.position.y;
float u = hypotf(dx, dy);
if (u != 0) {
CGVector v = CGVectorMake(2.0 * dx/u, 2.0 * dy/u);
[node.physicsBody applyForce:v];
}
}];
}
#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:0.8]
– (SKColor*)color:(int)i
{
switch (i) {
case 0:
return ColorHex(0xDA0734);
case 1:
return ColorHex(0xF1A20D);
case 2:
return ColorHex(0x4AABB1);
case 3:
return ColorHex(0x3F1833);
case 4:
return ColorHex(0xFCF3E7);
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 = [[SpinScene alloc] initWithSize:spriteView.frame.size];
[spriteView presentScene:scene];
}
@end