【问题标题】:Cannot detect touch on falling SKShapeNode // SpriteKite在下降的 SKShapeNode 上无法检测到触摸 // SpriteKite
【发布时间】:2018-06-23 20:38:59
【问题描述】:

我在 GameScene.swift 中有一个炸弹生成器,它将 SKShapeNodes 添加到场景中。每个 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")
        }
    }
}

【问题讨论】:

  • 我不是游戏专家,我从来没有这样做过。但我认为您想在实例化每个炸弹对象时为其添加一个触摸手势识别器。
  • 我认为This RayWenderlich Tutorial 应该可以帮助您解决问题。

标签: ios swift sprite-kit sknode


【解决方案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 {
//...
}

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多