[英]SKSpriteNode subclassing swift
我已經找到了一些帖子,但我仍然對如何做到這一點感到困惑。 我知道我必須使用“指定的初始化程序”,它是init(紋理:SKTexture!,顏色:UIColor!,大小:CGSize)。 真的,我還是不會用它。 我想向sprite節點添加一些屬性。
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 有關幫助,請參閱有關初始化程序的Swift文檔: https : //developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_323
希望這可以幫助,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.