大家好!
写了为我生成播放器的代码:
class PlayerPlane: SKSpriteNode {
static func populatePlayerPlane() -> SKSpriteNode {
let playerPlane = SKSpriteNode(imageNamed: "airplane_1_14")
playerPlane.position = CGPoint(x: 200, y: 200)
playerPlane.zPosition = 50
return playerPlane
}
func fireEnemies() {
print("Attack")
}
}
因为它是用SKSpriteNode
生成的,所以我无法附加方法fireEnemies。现在我无法将其从SKSpriteNode
转移到PlayerPlane
。
当然,我可以使用PlayerPlane
初始化程序完成所有其他方式,但可能是我错过了一些其他更智能的解决方案,用于将方法 fireEmenies 附加到 PlayerPlane
答案 0 :(得分:0)
如果您需要PlayerPlane
作为一个类,那么您可以这样做(因为PlayerPlane
是SKSpriteNode
的子类,您可以使用它的初始值设定项):
class PlayerPlane: SKSpriteNode {
static func populatePlayerPlane() -> PlayerPlane {
let playerPlane = PlayerPlane(imageNamed: "airplane_1_14")
playerPlane.position = CGPoint(x: 200, y: 200)
playerPlane.zPosition = 50
return playerPlane
}
func fireEnemies() {
print("Attack")
}
}
但您也可以使用协议并为SKSpriteNode
编写扩展名,如果您想让其他对象/结构体采用PlayerPlane
功能,这很方便:
protocol PlayerPlane {
func fireEnemies()
}
extension SKSpriteNode : PlayerPlane {
func fireEnemies() {
print("Attack")
}
}
extension SKSpriteNode {
static func populatePlayerPlane() -> SKSpriteNode {
let playerPlane = SKSpriteNode(imageNamed: "airplane_1_14")
playerPlane.position = CGPoint(x: 200, y: 200)
playerPlane.zPosition = 50
return playerPlane
}
}
最后,如果您希望以“其他”方式将fireEnemies
功能附加到PlayerPlane
,您还可以为协议编写扩展程序:
class PlayerPlane: SKSpriteNode {
static func populatePlayerPlane() -> PlayerPlane {
let playerPlane = PlayerPlane(imageNamed: "airplane_1_14")
playerPlane.position = CGPoint(x: 200, y: 200)
playerPlane.zPosition = 50
return playerPlane
}
}
protocol FireEnemies {
func fireEnemies()
}
extension PlayerPlane : FireEnemies {
func fireEnemies() {
print("Attack")
}
}