I have the following function which spawns squares and adds them to an array of squares. This adds new squares indefinitely until the function is stopped. The array of squares is declared in the SKScene
like so: var rsArray = [RedSquare]()
.
func spawnRedSquares() {
if !self.gameOver {
let rs = RedSquare()
var rsSpawnRange = self.frame.size.width/2
rs.position = CGPointMake(rsSpawnRange, CGRectGetMaxY(self.frame) + rs.sprite.size.height * 2)
rs.zPosition = 3
self.addChild(rs)
self.rsArray.append(rs)
let spawn = SKAction.runBlock(self.spawnRedSquares)
let delay = SKAction.waitForDuration(NSTimeInterval(timeBetweenRedSquares))
let spawnThenDelay = SKAction.sequence([delay, spawn])
self.runAction(spawnThenDelay)
}
}
I'm trying to use the touchesBegan()
function to detect when a specific square in the array is tapped and then access the properties of the square. I can't figure out how to determine which square is being touched. How would I go about doing this?
I was able to answer my own question by experimenting, and decided that I would post the answer in case anyone else had a similar problem. The code that I needed inside the touchesBegan()
function was the following:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let rsCurrent = self.nodeAtPoint(location)
for RedSquare in rsArray {
let rsBody = RedSquare.sprite.physicsBody
if rsBody == rsCurrent.physicsBody? {
//Action when RedSquare is touched
}
}
}
}