通過繼承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!
'updateTexture'不需要,'button.texture = newTexture'也可以,如果你需要在設置過程中做其他事情,只需重寫子類中的屬性 – Knight0fDragon
你們讓我感到驚訝 - 非常感謝! – boehmatron
@ Knight0fDragon感謝您的評論,你是對的!我在我的子類中使用該方法的原因是因爲我幾乎總是在同一時間做一些其他調整,例如使用SKActions旋轉精靈或以某種方式縮放精靈。 – zeeple