2016-02-03 36 views
1

我想添加一個精靈到我的遊戲場景。但事情是,我想多次添加精靈,所以我想要從精靈中創建一個類,我不想使用場景編輯器如何將Sprite作爲類添加到場景中?

所以我的類被稱爲乘客,這是它

import SpriteKit 

class PassengerNode: SKSpriteNode, CustomPassengerNodeEvents { 

init(texture: SKTexture?, color: UIColor, size: CGSize) { 
    <#code#> 
} 
} 

在我的遊戲場景代碼,我想補充像

let passenger = PassengerNode() 

的類,但我不知道如何可以在客運班內設置的質感?我無法弄清楚這一點?任何提示或建議?

在此先感謝

回答

1

通過繼承SKSpriteNode,你絕對是在正確的軌道上。當我創建一個看起來像這樣的SKSpriteNode子類時,我使用了一個標準模板。

import Foundation 
import SpriteKit 

class SubclassedSKSpriteNode: SKSpriteNode { 
    init() { 
     let texture = SKTexture(imageNamed: "whateverImage.png") 
     super.init(texture: texture, color: UIColor.clearColor(), size: texture.size()) 
     userInteractionEnabled = true 
    } 

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

    // MARK: - Change Texture 

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

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     let location = (touches.first!).locationInNode(scene!) 
     position = scene!.convertPoint(location, toNode: parent!) 

     print("touchesBegan: \(location)") 
    } 

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     let location = (touches.first!).locationInNode(scene!) 
     position = scene!.convertPoint(location, toNode: parent!) 

     print("touchesMoved: \(location)") 

    } 

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     let location = (touches.first!).locationInNode(scene!) 
     position = scene!.convertPoint(location, toNode: parent!) 

     print("touchesEnded: \(location)") 
    } 
} 

而且,這個按鈕添加到您的SKScene(或任何其他SKNode):另外,我有一個可以從類的外部調用紋理改變任何你喜歡的功能,增強其

let button = SubclassedSKSpriteNode() 
button.position = CGPointMake(420, 300) 
addChild(button) 

然後,如果你想改變紋理,請致電:

button.updateTexture(newTexture) 

HTH!

+2

'updateTexture'不需要,'button.texture = newTexture'也可以,如果你需要在設置過程中做其他事情,只需重寫子類中的屬性 – Knight0fDragon

+0

你們讓我感到驚訝 - 非常感謝! – boehmatron

+0

@ Knight0fDragon感謝您的評論,你是對的!我在我的子類中使用該方法的原因是因爲我幾乎總是在同一時間做一些其他調整,例如使用SKActions旋轉精靈或以某種方式縮放精靈。 – zeeple

1

你只需要調用一個super.init之前設置所有的屬性。您可以創建一個默認的init()函數,並設置你的屬性,然後調用具有質感super.init等

class SomeSprite: SKSpriteNode { 
    init() { 
     let spriteTexture: SKTexture = SKTexture(imageNamed: "someImage") 
     let spriteSize = spriteTexture.size() 
     super.init(texture: spriteTexture, color: UIColor.clearColor(), size: spriteSize) 
    } 
} 

你說的沒錯,你需要調用init(texture:color:size),因爲它是SKSpriteNode指定初始化。但是您應該知道,您可以從子類中的另一個init函數中調用指定的初始化程序,在這種情況下爲空白init實現。只需設置您的默認值並創建精靈。

相關問題