答案没有你想象的那么复杂。好吧,代码可能会更复杂一些,但是一旦掌握了结构,它就会变得最灵活。创建不同类型的宇宙飞船也将更具可读性。
您可以重写子类中的初始化方法。作为旁注,使用(instancetype)
代替(id)
(来源:实例类型@NSHipster http://nshipster.com/instancetype/).
当您向对象添加自定义主体精灵时,我会选择子类化 SKNode 而不是 SKSpriteNode (所以@interface SpaceshipNode : SKNode
代替@interface SpaceshipNode : SKSpriteNode
).
@interface SpaceshipNode : SKNode
@property SKColor * color; // Use SKColor instead of NSColor
@property CGFloat engineThrust;
@end
// ...
@implementation SpaceshipNode
- (instancetype) init {
if (self == [super init]) {
NSLog(@"A new SpaceshipNode was just init'ed.");
// set some default initial values here that all brand-new SpaceshipNodes will inherit
// perhaps create and add a basic body sprite
// SKSpriteNode * body = ...;
// [self addChild:body];
// set thrust
self.engineThrust = 2.0;
}
return self;
}
然后你可以继承并创建一种新型的宇宙飞船。惊人的!
@interface DestroyerSpaceship : SpaceshipNode
@property CGFloat missileThrust;
@end
@implementation DestroyerSpaceship
- (instancetype) init {
// note that [super init] will call the SpaceshipNode's init method
if (self = [super init]) {
NSLog(@"A new DestroyerSpaceship was just init'ed.");
// add a body sprite
// SKSpriteNode * body = ...;
// [self addChild:body];
// a Destroyer is much faster than your average spaceship
self.engineThrust = 10.0;
// set class specific variables
self.missileThrust = 5.f;
}
return self;
}
现在,您只需调用:
SpaceshipNode * newSpaceShip = [SpaceshipNode new]; // short for [[SpaceshipNode alloc] init];
DestroyerSpaceship * newDestroyer = [DestroyerSpaceship new];
这两行将记录以下内容。最后两行是由 Destroyer 引起的,它首先调用SpaceshipNode
init
,然后是特定于驱逐舰的init
method.
一个新的 SpaceshipNode 刚刚启动。
一个新的 SpaceshipNode 刚刚启动。
一艘新的驱逐舰宇宙飞船刚刚启动。
你甚至可以像这样使用它:
SpaceshipNode * newUnidentifiedVessel = [DestroyerSpaceship new];
if ([newUnidentifiedVessel isKindOfClass:[DestroyerSpaceship class]]) {
NSLog(@"We are under attack! Route power to shields!");
}