WatchKit3からSceneKitやSpriteKitが使用できるようになった。
SceneKitを使用することで3Dのアプリケーションを作成することが可能になったが、何かテキストを表示させる場合は2Dで表示したいことがあります。
WatchOS3でSceneKitを使用して上記のことをしたい場合のソースコードを公開します。
ポイントとしてはSceneKitのWKInterfaceSCNSceneにSpriteKitのシーンをオーバーレイ表示させるだけです。
InterfaceController.h
#import <WatchKit/WatchKit.h>
#import <Foundation/Foundation.h>
@interface InterfaceController : WKInterfaceController
{
}
@end
InterfaceController.m
#import "InterfaceController.h"
#import <SpriteKit/SpriteKit.h>
@interface InterfaceController()
{
}
@property (strong, nonatomic) IBOutlet WKInterfaceSCNScene *scnInterface;
@end
@implementation InterfaceController
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
SCNScene *scene = [SCNScene sceneNamed:@"art.scnassets/caracter.dae"];
// Create and add a camera to the scene
SCNNode *cameraNode = [SCNNode node];
cameraNode.camera = [SCNCamera camera];
[scene.rootNode addChildNode:cameraNode];
// Place the camera
cameraNode.position = SCNVector3Make(0, 0, 25);
// Create and add a light to the scene
SCNNode *lightNode = [SCNNode node];
lightNode.light = [SCNLight light];
lightNode.light.type = SCNLightTypeOmni;
lightNode.position = SCNVector3Make(0, 10, 10);
[scene.rootNode addChildNode:lightNode];
// Create and add an ambient light to the scene
SCNNode *ambientLightNode = [SCNNode node];
ambientLightNode.light = [SCNLight light];
ambientLightNode.light.type = SCNLightTypeAmbient;
ambientLightNode.light.color = [UIColor darkGrayColor];
[scene.rootNode addChildNode:ambientLightNode];
// Retrieve the ship node
ship = (SCNNode *)[scene.rootNode childNodeWithName:@"Armature" recursively:YES];
//ship.scale = SCNVector3Make(0.1f, 0.1f, 0.1f);
ship.rotation = SCNVector4Make(0, 0, 0, M_PI);
// Set the scene to the view
self.scnInterface.scene = scene;
// Show statistics such as fps and timing information
self.scnInterface.showsStatistics = YES;
// ---------------------------------------------------
// SpriteKitでシーンを作成するそこにLabelを貼る
// WKInterfaceSCNSceneのoverlaySKSceneプロパティーに作成したSpriteKitのシーンを代入
// 要するにSpriteKitのシーンをオーバーレイ表示させる
// ---------------------------------------------------
SKScene *skScene = [SKScene sceneWithSize:CGSizeMake(self.contentFrame.size.width, self.contentFrame.size.height)];
SKLabelNode *label = [SKLabelNode labelNodeWithFontNamed:@"Courier"];
label.text = @"Hello";
label.fontSize = 20;
label.position = CGPointMake(100, 100);
[skScene addChild:label];
_scnInterface.overlaySKScene = skScene;
}
- (void)willActivate {
[super willActivate];
}
- (void)didDeactivate {
[super didDeactivate];
}
@end