我如何将实例方法连接到我的对象

时间:2017-04-19 08:23:29

标签: swift sprite-kit

大家好!

写了为我生成播放器的代码:

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

1 个答案:

答案 0 :(得分:0)

如果您需要PlayerPlane作为一个类,那么您可以这样做(因为PlayerPlaneSKSpriteNode的子类,您可以使用它的初始值设定项):

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")
    }
}