丸の中に数字とそのかずの角をもつ多角形を表示するiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@import SpriteKit;
@interface ViewController ()
@property (nonatomic, weak) SKScene *scene;
@property (nonatomic) int count;
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
[self setupScene];
[self createV];
}
– (void)setupScene {
SKView *sv = [[SKView alloc] initWithFrame:self.view.bounds];
SKScene *s = [SKScene sceneWithSize:sv.frame.size];
s.backgroundColor = [self color:0];
[sv presentScene:s];
[self.view addSubview:sv];
self.scene = s;
}
– (void)createV {
for (int i=0; i<2; i++) {
SKSpriteNode *bar = [SKSpriteNode spriteNodeWithColor:[UIColor lightGrayColor] size:CGSizeMake(300, 10)];
bar.anchorPoint = (i==0) ? CGPointMake(1.2, 0.5) : CGPointMake(-0.2, 0.5);
bar.position = CGPointMake(CGRectGetMidX(self.view.bounds), 100);
bar.zRotation = (i==0) ? –M_PI * 0.3 : M_PI * 0.3;
bar.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:bar.size center:(i==0) ? CGPointMake(-200, 5) : CGPointMake(200, 5)];
bar.physicsBody.dynamic = NO;
[self.scene addChild:bar];
}
}
– (void)createBall:(CGPoint)p number:(int)n {
SKShapeNode *ball = [SKShapeNode shapeNodeWithCircleOfRadius:30];
ball.position = p;
ball.fillColor = [self color:arc4random_uniform(4) + 1];
ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:30];
ball.physicsBody.dynamic = YES;
[self.scene addChild:ball];
float r = 22;
if (n < 3) {
SKShapeNode *c = [SKShapeNode shapeNodeWithCircleOfRadius:r];
c.fillColor = [self color:0];
[ball addChild:c];
} else {
float dAngle = 2.0 * M_PI / n;
UIBezierPath *path = [UIBezierPath bezierPath];
for (int i=0; i<n; i++) {
CGPoint p = CGPointMake(r * cos(dAngle * i), r * sin(dAngle * i));
if (i == 0) [path moveToPoint:p];
else [path addLineToPoint:p];
}
[path closePath];
SKShapeNode *po = [SKShapeNode shapeNodeWithPath:path.CGPath];
po.fillColor = [self color:0];
[ball addChild:po];
}
SKLabelNode *l = [SKLabelNode labelNodeWithText:[NSString stringWithFormat:@”%d”, n]];
l.fontName = @”AvenirNext-Heavy”;
l.fontColor = ball.fillColor;
l.verticalAlignmentMode = SKLabelVerticalAlignmentModeCenter;
[ball addChild:l];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
++self.count;
CGPoint p = [[touches anyObject] locationInNode:self.scene];
[self createBall:p number:self.count];
}
#define ColorHex(rgb) [UIColor colorWithRed:((rgb & 0xFF0000) >> 16)/255.0 green:((rgb & 0xFF00) >> 8)/255.0 blue:(rgb & 0xFF)/255.0 alpha:1.0]
– (UIColor *)color:(int)i {
if (i > 4) return nil;
int colorCode[] = {0xF2F2F2, 0x049DD9, 0x03A688, 0x6773AF, 0xC7D943};
return ColorHex(colorCode[i]);
}
@end