检测阵列中 SKNode 上的触摸

Detect Touches on SKNode in Array

我有以下函数生成正方形并将它们添加到正方形数组中。这会无限期地添加新方块,直到函数停止。正方形数组在 SKScene 中声明如下: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)
    }
}

我正在尝试使用 touchesBegan() 函数来检测数组中特定方块何时被点击,然后访问该方块的属性。我不知道如何确定正在触摸哪个方块。我该怎么做?

为您生成的每个方块指定一个唯一的名称,并在 touchesBegan 中检查该名称。您可以使用计数器并执行

rs.name = "square\(counter++)"

在 touchesBegan 中,您可以检索被触摸节点的名称,并将其与数组中节点的名称进行核对。

首先你必须给 rs node 一个名字。例如

rs.name = "RedSquare"

然后您可以使用nodeAtPoint函数来查找特定接触点处的节点。如果节点是RedSquare,可以修改

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    for touch in touches {

        let touchPoint = touch.locationInNode(self)
        let node = self.nodeAtPoint(touchPoint)

        if node.name == "RedSquare" {
            // Modify node
        }

    }
}

我能够通过实验回答我自己的问题,并决定我会 post 回答以防其他人遇到类似问题。 touchesBegan() 函数中我需要的代码如下:

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
            }
        }
    }
}