ニッコリした六角を積み上げるiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@import SpriteKit;
@interface ViewController () <SKSceneDelegate>
@property (nonatomic, weak) SKScene *scene;
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
[self setupScene];
[self createGround];
}
– (void)setupScene
{
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [SKScene sceneWithSize:spriteView.frame.size];
scene.delegate = self;
scene.backgroundColor = [SKColor colorWithHue:0.3 saturation:0.1 brightness:1 alpha:1];
[spriteView presentScene:scene];
self.scene = scene;
}
– (void)createGround
{
SKSpriteNode *ground = [SKSpriteNode spriteNodeWithColor:[SKColor colorWithHue:0.1 saturation:0.3 brightness:1 alpha:1] size:CGSizeMake(CGRectGetMaxX(self.view.bounds), 10)];
ground.position = CGPointMake(CGRectGetMidX(self.view.bounds), 80);
[self.scene addChild:ground];
ground.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:ground.size];
ground.physicsBody.dynamic = NO;
}
– (void)smileAtPoint:(CGPoint)p
{
float r = 20;
float anglel = M_PI / 3.0;
UIBezierPath *path = [UIBezierPath bezierPath];
for (int i=0; i<6; i++) {
float x = r * cos(anglel * i);
float y = r * sin(anglel * i);
if (i == 0) {
[path moveToPoint:CGPointMake(x, y)];
} else {
[path addLineToPoint:CGPointMake(x, y)];
}
}
float hue = (arc4random() % 10) * 0.1;
SKShapeNode *hex = [SKShapeNode node];
hex.name = @”hex”;
hex.path = path.CGPath;
hex.fillColor = [SKColor colorWithHue:hue saturation:0.1 brightness:0.8 alpha:1];
hex.position = p;
[self.scene addChild:hex];
SKLabelNode *smile = [SKLabelNode node];
smile.text = @”o^o”;
smile.fontName = @”ChalkboardSE-Bold”;
smile.fontSize = 16;
smile.verticalAlignmentMode = SKLabelVerticalAlignmentModeCenter;
smile.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeCenter;
[hex addChild:smile];
hex.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:path.CGPath];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self.scene];
[self smileAtPoint:p];
}
– (void)update:(NSTimeInterval)currentTime forScene:(SKScene *)scene
{
[scene enumerateChildNodesWithName:@”hex” usingBlock:^(SKNode *node, BOOL *stop) {
if (node.position.y < –30) {
[node removeFromParent];
}
}];
}
– (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end