【问题标题】:SpriteKit: How to make touchesBegan work for node not on the highest zPositionSpriteKit:如何使 touchesBegan 为不在最高 zPosition 上的节点工作
【发布时间】:2021-07-06 20:31:51
【问题描述】:

我正在制作一个 SpriteKit 游戏,它的按钮节点位于最高 zPosition。我正在重写 touchesBegan 函数以向按钮添加功能。它之所以有效,是因为该按钮位于 z 维度中的最高位置。与任何其他节点相比,.zPosition 设置为最高数量。我需要在场景中有另一个按钮,但它需要有一个较低的 .zPosition 因为它需要在某个点被另一个节点覆盖。当我的 .zPosition 低于另一个节点时,不会触发 touchesBegan 方法。如果我有更高的 .zPosition 则它可以工作,但这会使另一个按钮节点不起作用。无论 .zPosition 是什么,如何使 touchesBegan 方法工作?请向我询问更多说明。谢谢!

【问题讨论】:

    标签: ios swift sprite-kit skspritenode touchesbegan


    【解决方案1】:

    您想使用 nodes(at:) 方法。这是一个特定点的所有节点的数组,该点就是你触摸的地方。

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    
    for t in touches {
      let location = t.location(in: self)
      let touchedNodes = self.nodes(at: location) // Array of all nodes at the point
      
      for node in touchedNodes { // Iterate through all nodes in the touchedNode array
        if node.name == "your button node" {
        ... // Add your button code here
        }
      }
    }
        
    }
    

    【讨论】:

      【解决方案2】:

      一旦您在 touchesBegan 中获得了点,您是否尝试测试按钮节点是否包含该点:

      func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) -> Bool {
          if touches.count == 1 {
              if let touch = touches.first {
                  let location = touch.location(in: self)
                  if myButtonNode.contains(location) {
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 2018-03-13
        • 1970-01-01
        • 1970-01-01
        • 2013-10-25
        相关资源
        最近更新 更多