SpriteKit remembering which sprite was touched

70 Views Asked by At

I have a 'game' with 3 sprites. If a user clicks 'Sprite1', and thereafter 'Sprite2'. Is there some way to remember which sprites were pressed? Its only for 2 sprites if there are more i will need to empty the 'memory' and start over with the last one 'touched', i didn't want to work with booleans.

All my sprites have the .name attribute so i can acces them there.

would an IF statement be sufficient like so

var spriteArr:[String] = []
let location = (touch as UITouch).locationInNode(self)
for touch in touches{
   if spriteArr.count < 2 {
        spriteArr.append(self.nodeAtPoint(location))
   }else{
      spriteArr.removeAll
      spriteArr.append(self.nodeAtPoint(location))
   }
}
1

There are 1 best solutions below

1
On BEST ANSWER

You can check the Sprites by accessing the .name of the Node and storing the names in an array like this.

 var nodeNames:[String] = []
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {         
        let touch = touches.first as! UITouch
        var touchedNode:SKNode = nodeAtPoint(touch.locationInNode(self))

        if(nodeNames.count > 2){
             nodeNames = []
        }
        if(touchedNode.name != nil){
            if(!contains(nodeNames, touchedNode.name)){
                 nodeNames.append(touchedNode.name)
            }
        }
    }