【问题标题】:Touch duration in SpriteKitSpriteKit 中的触摸持续时间
【发布时间】:2021-11-28 08:10:31
【问题描述】:

我目前正在使用 SpriteKit,只要用户正在触摸某个 SpriteNode,我就想在更新循环中运行一个代码块。我尝试通过使用布尔值来实现这一点,当 touchesBegan() 方法识别到此节点上的触摸并设置为 false 时,设置为 true,当 touchesEnded() 方法识别到此节点上的触摸结束时。但是,当用户触摸节点然后将手指移出边界时,touchesEnded() 方法无法识别。

有没有一种简单的方法来检查从该节点开始但随后移出该节点的触摸是否仍然存在?或者我可以检查一下 UITouch 实例是否仍然存在?

【问题讨论】:

    标签: swift sprite-kit touch uitouch


    【解决方案1】:

    不清楚您想要什么行为,但一般来说,您可能希望使用触摸身份来跟踪正在发生的事情。

    例如,如果您正在处理包含节点的场景中的触摸,并且希望只是在触摸节点时开始动作并在触摸结束时停止动作,那么类似:

    // Whatever touch initiated the action
    var activeTouch: UITouch?
    // Checked by update loop
    var doingSomething = false
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
      for touch in touches {
        // Ignore new touches if one is already active
        guard activeTouch == nil else { return }
        let location = touch.location(in: self)
        let touchedNodes = self.nodes(at: location)
        for node in touchedNodes {
          if <some test for the interesting node> {
            activeTouch = touch
            doingSomething = true
          }
        }
      }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
      for touch in touches {
        if touch == activeTouch {
          // Finished
          activeTouch = nil
          doingSomething = false
        }
      }
    }
    

    如果您还希望在用户将手指从节点上移开时停止操作并在他们移回节点时重新启动,则还需要覆盖 touchesMoved,例如:

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
      for touch in touches {
        if touch == activeTouch {
          let location = touch.location(in: self)
          let touchedNodes = self.nodes(at: location)
          // Assume they moved off the node
          doingSomething = false
          for node in touchedNodes {
            if <some test for the interesting node> {
              // Nope, still touching it
              doingSomething = true
            }
          }
        }
      }
    }
    

    (您还应该以某种适当的方式处理touchesCancelled,可能会停止操作并清除activeTouch,如touchesEnded)

    当有多个触摸处于活动状态时,您可能会考虑其他一些行为。您可能需要跟踪所有活动的触摸以及它们在节点上或关闭的状态,然后如果节点上有任何活动的触摸,则设置doingSomething = true。或者,您可能希望touchesMoved 在离开节点后立即放弃活动触摸,因此再次重新打开该触摸不会重新激活。

    主要的一点是,跟踪触摸身份为您提供了很大的灵活性,但您必须决定您希望游戏如何反应。

    【讨论】:

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