針が一周すると10秒になるカンタンなタイマーをiPhoneアプリで描いてみます。
動作イメージ
XcodeからiOS7 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface TimerScene : SKScene
@property BOOL contentCreated;
@property (strong, nonatomic) SKSpriteNode *hand;
@property (strong, nonatomic) SKLabelNode *time;
@property (strong, nonatomic) NSDate *start;
@end
@implementation TimerScene
– (void)didMoveToView:(SKView *)view
{
if (!self.contentCreated) {
[self createSceneContents];
self.contentCreated = YES;
}
}
– (void)createSceneContents
{
self.backgroundColor = [SKColor grayColor];
self.scaleMode = SKSceneScaleModeAspectFit;
SKSpriteNode *clock = [SKSpriteNode spriteNodeWithImageNamed:@”clockframe.png”];
clock.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:clock];
self.hand = [SKSpriteNode spriteNodeWithImageNamed:@”hand.png”];
self.hand.anchorPoint = CGPointMake(0.2, 0.5);
self.hand.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:self.hand];
SKAction *rotate = [SKAction rotateByAngle:M_PI/2.0 duration:1.0];
[self.hand runAction:rotate];
self.time = [[SKLabelNode alloc] initWithFontNamed:@”AppleSDGothicNeo-Thin”];
self.time.fontSize = 80;
self.time.fontColor = [UIColor lightGrayColor];
self.time.text = @”10s”;
self.time.position = CGPointMake(160, 150);
[self addChild:self.time];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
SKAction *rotate = [SKAction rotateByAngle:-2.0*M_PI duration:10.0];
[self.hand runAction:rotate];
self.start = [NSDate date];
}
– (void)didSimulatePhysics
{
NSTimeInterval t = [self.start timeIntervalSinceNow];
int minutes = floor(t/60);
int seconds = trunc(t – minutes * 60) – 49;
if (seconds >= 0) {
self.time.text = [NSString stringWithFormat:@”%ds”, seconds];
}
}
@end
@interface ViewController ()
@property (strong, nonatomic) SKView *spriteView;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.spriteView];
TimerScene *timerScene = [[TimerScene alloc] initWithSize:CGSizeMake(320, 568)];
[self.spriteView presentScene:timerScene];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end