产生具有相同属性的多个精灵节点

时间:2016-01-22 09:07:51

标签: ios swift nodes skspritenode

我正在尝试制作一个游戏,它会产生从屏幕顶部下来的节点。我希望我的程序可以从具有相同属性的众多节点中进行选择(但它们看起来不同)。是否有一种方法可以创建一个节点数组,我可以同时应用这些属性,而不是必须遍历每个节点并反复对齐它们。 我是初学者编码器,除了我已经拥有的变量外,没有任何代码可以显示。

    var SY = SKSpriteNode(imageNamed: "slowYellow")
    let SG = SKSpriteNode(imageNamed: "slowGreen")
    let SP = SKSpriteNode(imageNamed: "slowPurple")
    let SR = SKSpriteNode(imageNamed: "slowRed")
    let FY = SKSpriteNode(imageNamed: "fastYellow")
    let FG = SKSpriteNode(imageNamed: "normalGreen")
    let FP = SKSpriteNode(imageNamed: "normalPurple")
    let FR = SKSpriteNode(imageNamed: "fastRed")
    let NY = SKSpriteNode(imageNamed: "normalYellow")
    let NG = SKSpriteNode(imageNamed: "normalGreen")
    let NP = SKSpriteNode(imageNamed: "normalPurple")
    let NR = SKSpriteNode(imageNamed: "normalRed")
    let SB = SKSpriteNode(imageNamed: "slowBlack")
    let NB = SKSpriteNode(imageNamed: "normalBlack")
    let FB = SKSpriteNode(imageNamed: "fastBlack")

1 个答案:

答案 0 :(得分:0)

这听起来像是子类化

的理想候选者

Subclassing允许您为给定的超类(在您的情况下为SKSpriteNode设置常用功能。这将允许您创建具有相同基本功能的多个对象。

您可以创建自己的便利初始化程序(it's not technically overriding SKSpriteNode's convenience init)并在那里设置常用属性。例如:

class MyCustomNode: SKSpriteNode {

    convenience init(imageNamed name:String) {

        let tex = SKTexture(imageNamed: name);
        let nodeSize = CGSizeMake(50, 50);

        self.init(texture: tex, color: UIColor.clearColor(), size: nodeSize)

        // Do extra setup for common functionality here
    }  
}

然后,为了使用它,我建议您创建一个图像名称数组,并在for循环中创建节点。例如:

let birds :[String] = ["slowYellow", "slowGreen", "slowPurple", "slowRed", "fastYellow", "fastGreen", "fastPurple", "fastRed", "normalYellow", "normalGreen", "normalPurple", "normalRed", "slowBlack", "normalBlack", "fastBlack"]

var birdNodes = [MyCustomNode]()
for bird in birds {
    let node = MyCustomNode(imageNamed: bird)
    node.position = // do position logic
    addChild(node)
    birdNodes.append(node)
}

然后,您可以通过birdNodes数组引用您的鸟精灵。

您还可以通过覆盖更多函数来进一步自定义子类。

我建议您查看Swift documentation on inheritance。这将为您提供子类化的良好开端。