无法检测到落下的 SKShapeNode // SpriteKite 上的触摸

Cannot detect touch on falling SKShapeNode // SpriteKite

我在 GameScene.swift 中有一个炸弹生成器,可以将 SKShapeNode 添加到场景中。每个 SKShapeNode 都是一个落下的物理对象,名称设置为 "bomb"。我想检测用户何时触摸这些节点(中秋使用 touchesBegan),但它不起作用。我做错了什么?

// Bomb Spawner Function
func spawnBomb() {
    let bombHeight = 80
    let bomgWidth = 40
    // Define Bomb
    let bomb = SKShapeNode(rectOf: CGSize(width: bomgWidth,
                                          height: bombHeight))
    bomb.name = "bomb"
    bomb.zPosition = 10
    bomb.isUserInteractionEnabled = true
    bomb.position = CGPoint(x: size.width / 2, y:  size.height / 2)
    bomb.fillColor = SKColor.blue
    // Add Physics Body
    bomb.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: bomgWidth,
                                                         height: bombHeight))
    // Determine Random Position
    let randomPosition = abs(CGFloat(random.nextInt()).truncatingRemainder(dividingBy: size.width))
    bomb.position = CGPoint(x: randomPosition, y: size.height)
    // Add Category BitMask
    bomb.physicsBody?.categoryBitMask = BombCategory
    bomb.physicsBody?.contactTestBitMask = WorldFrameCategory
    // Add to the scene
    addChild(bomb)

}

触摸检测

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch:UITouch = touches.first!
    let positionInScene = touch.location(in: self)
    let touchedNode = self.atPoint(positionInScene)

    if let name = touchedNode.name
    {
        if name == "bomb"
        {
            print("bomb Touched")
        }
    }
}

我怀疑您的问题源于 atPoint returns 一个 SKNode。您有两种获取最顶层节点的方法:

if atPoint(touch.location(in: self)) == childNode(withName: "bomb"){
//run your code
}

这对单个节点来说没问题。就个人而言,我喜欢使用 subclass,所以我会使用

class炸弹:SKShapeNode

然后简单地看一下我触摸到的最上面的节点是否可以施放炸弹。

if let bomb = atPoint(touch.location(in: self)) as? Bomb {
//...
}

这让您可以将典型的炸弹设置移动到子class 中,并使整体代码更具可读性。