panzerblitzer panzerblitzer - 1 month ago 7x
Swift Question

Iterate array of SKShapeNodes

Struggling with how to iterate through an array of SKShapeNodes. I seem to be able to go through it in DidMoveToView(), but, not WhenTouchesBegan().

From 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

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

What is frustrating is if I use a series of if...else if...else if I can check every single area, but, can't check them through the array.


not quite clear about your target. if you simply want a way to iterate child nodes, you can try

//init child nodes
for i in 1...2{
  let areaNode = SKShapeNode()
  ... = "area"

for node in parentNode.children{
  if == "area"{
    print("here we find a child area")
    print("some irrelevant node found")

Btw, the reason why your code in didMoveToView() work is you declared an new areas array, which in fact is an in-method variable replaced the role of previous class property areas