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

时间:2018-06-23 20:38:59

标签: ios swift sprite-kit sknode

我在GameScene.swift中有一个炸弹生成器,可以将SKShapeNodes添加到场景中。每个SKShapeNode是一个下落的物理对象,其名称设置为“炸弹”。我想检测用户何时触摸这些节点(使用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")
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我怀疑您的问题源于atPoint返回SKNode的事实。您有两种获取最高节点的方法:

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

这对于单个节点很好。就个人而言,我喜欢使用子类,因此我将使用

类炸弹:SKShapeNode

,然后简单地查看我触摸下的最高节点是否可以转换为炸弹。

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

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