苦苦思索如何遍历 SKShapeNode 数组。我似乎可以在 DidMoveToView() 中完成它,但不能在 WhenTouchesBegan() 中完成。
来自 GameScene.swift:
class GameScene: SKScene {
...
var areaTwo = SKShapeNode()
var areaThree = SKShapeNode()
var areaFour = SKShapeNode()
var currentArea = SKShapeNode()
//CGPaths as UIBezierPaths set here
var areas = [SKShapeNode]()
override func didMoveToView(view: SKView) {
...
areaTwo = SKShapeNode(path: areaTwoPath.CGPath)
areaThree = SKShapeNode(path: areaThreePath.CGPath)
areaFour = SKShapeNode(path: areaFourPath.CGPath)
let areas = [areaTwo, areaThree, areaFour]
...
//this works
for area in areas {
area.lineWidth = 4
addChild(area)
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
currentArea.fillColor = UIColor.clearColor()
//this does not work! No errors thrown. Just doesn't seem to do anything.
for area in areas{
currentArea = area
if currentArea.containsPoint(location) {
currentArea.fillColor = UIColor.redColor()
}
}
}
}
令人沮丧的是,如果我使用一系列 if...else if...else if 我可以检查每个区域,但无法通过数组检查它们。
最佳答案
不太清楚你的目标。如果你只是想要一种迭代子节点的方法,你可以尝试
//init child nodes
for i in 1...2{
let areaNode = SKShapeNode()
...
areaNode.name = "area"
parentNode.addChild(areaNode)
}
//iteration
for node in parentNode.children{
if node.name == "area"{
print("here we find a child area")
}else{
print("some irrelevant node found")
}
}
顺便说一句,你的代码在 didMoveToView()
中工作的原因是你声明了一个新的 areas
数组,这实际上是一个方法内变量取代了上一类属性 areas
关于arrays - 迭代 SKShapeNodes 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39479037/