SKSpriteNode子类化swift
我发现了一些这方面的post,但我仍然困惑如何做到这一点。 我知道我必须使用init(texture:SKTexture!,color:UIColor!,size:CGSize)的“指定初始化程序”。 真的,我不会用那个。 我想只是添加一些属性的精灵节点。
class Piece: SKSpriteNode { enum Type: Int { case type1 = 1, type2, type3, type4, type5 } var piecetype : Type init(texture: SKTexture!, color: UIColor!, size: CGSize) { self.piecetype = .type1 super.init(texture: texture, color: color, size: size) } convenience init(imageNamed: String!, currentPiece: Type) { self.piecetype = currentPiece let color = UIColor() let texture = SKTexture(imageNamed: imageNamed) let size = CGSizeMake(100.0, 100.0) super.init(texture: texture, color: color, size: size) }
在主代码中,我尝试使用添加一块
var newPiece : Piece = Piece(imageNamed: "image.png", currentPiece: .type1) self.addChild(newPiece)
看起来好像我很接近,但是我对如何做初始化器感到困惑。
只需将您的convenience initializer
更改为:
convenience init(imageNamed: String!, currentPiece: Type) { let color = UIColor() let texture = SKTexture(imageNamed: imageNamed) let size = CGSizeMake(100.0, 100.0) self.init(texture: texture, color: color, size: size) self.piecetype = currentPiece }
在Swift中,一个convenience initializer
必须:
- 调用同一类的另一个便捷初始值设定项或该类的指定初始值设定项(不是超类)
- 调用
self.init[...]
后self.init[...]
使用selfself.init[...]
请参阅初始化程序的Swift文档以获取帮助: https : //developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_323
希望这可以帮助,