2016-09-13 96 views
1

如何遍歷SKShapeNodes數組。我似乎能夠在DidMoveToView()中通過它,但是,不是WhenTouchesBegan()。迭代SKShapeNodes數組

從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 ...否則,如果...否則,如果我可以檢查每一個區域,但是,不能檢查他們通過陣列。

+1

您有兩個'區域',一個實例屬性和一個局部let-constant。在哪裏給實例屬性'areas'賦值? – OOPer

+0

OOPer對此正確。你正在陰影'didMoveToView'中的區域。將'let areas = ...'更改爲'areas = ...' –

+0

DOH!這可能是問題! 謝謝! – panzerblitzer

回答

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

+0

謝謝你的額外指針。將嘗試並實施此。 – panzerblitzer