在如何遍历SKShapeNodes数组的过程中苦苦挣扎。我似乎能够在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如果我可以检查每个区域,但是,不能通过数组检查它们。
答案 0 :(得分:1)
对目标不太清楚。如果您只想要一种迭代子节点的方法,可以尝试
//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
的角色