gpt4 book ai didi

ios - 生成具有相同属性的多个 Sprite 节点

转载 作者:行者123 更新时间:2023-11-30 13:45:56 25 4
gpt4 key购买 nike

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

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

最佳答案

这听起来像是子类化的理想候选者

Subclassing允许您为给定的父类(super class)(在您的例子中为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 数组引用您的小鸟 Sprite 。

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

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

关于ios - 生成具有相同属性的多个 Sprite 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34942801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com