2016-02-13 102 views
0

我想初始化從SKSpriteNode繼承的自定義類。目前的類定義看起來像這樣添加自定義屬性到自定義類和初始化類

import SpriteKit 

class PassengerNode: SKSpriteNode { 
let passengerStart: Int = 2 
let passengerDestination: Int = 0 

init() { 
    let texture = SKTexture(imageNamed: "passenger1")   
    super.init(texture: texture, color: UIColor.clearColor(), size: texture.size()) 
    self.zPosition = 100 
} 

required init(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 

func updateTexture(newTexture: SKTexture) { 
    self.texture = newTexture 
} 

}

我想有passengerStart和passsengerDestination分配給對象,分別對類的實例。理想情況下,這兩個值都可以隨每個實例化而不同。

當我實例化類對象我覺得像

let newObject = PassengerNode(start: 1, destination: 0, texture: "passenger1") 

但是,我得到它的工作...如何,我需要改變我的初始化? 有人有幫助的想法嗎?

在此先感謝。

回答

0

你必須寫你的子類的init方法這需要那些 三個參數:

class PassengerNode: SKSpriteNode { 
    let passengerStart: Int 
    let passengerDestination: Int 

    init(start: Int, destination: Int, texture: String) { 
     let texture = SKTexture(imageNamed: texture) 
     passengerStart = start 
     passengerDestination = destination 
     super.init(texture: texture, color: UIColor.clearColor(), size: texture.size()) 
     self.zPosition = 100 
    } 

    required init(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    // ... more methods ... 
} 

init方法必須初始化子類的屬性和 然後調用super.init