touchesBegan,如何获得所有触摸,而不仅仅是第一次或最后一次?

touchesBegan, how to get all touches, not just first or last?

在 SpriteKit 的 SKSpriteNodes 和其他可见节点中,响应这些节点中的触摸通常以如下方式完成:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        if let touch = touches.first {...
 // do something with the touch location that's now in touch
// etc

这一切都很棒,但是如果我想确保我得到其中所有触摸的触摸信息(让我们想象一下...)SKSpriteNode 怎么办?

= touches.first 将条件限制为仅响应此 SKSpriteNode 内的第一次触摸。它是如何为这个 SKSpriteNode 中的所有触摸完成的,这样每个触摸都有其可用的位置,或者它所拥有和携带的任何其他东西。

我知道。愚蠢的问题。我就是那个人。我根本看不出这是怎么做到的。

通常视图不会响应多个触摸,除非 multipleTouchEnabled 属性 设置为 true

mySprite.multipleTouchEnabled = true

您会注意到方法 touchesBegan:event: 不是 return 单个 UITouch 对象,而是 UITouch 对象的集合(a.k.a。一个无序集合)。

在此方法中,您可以(例如)遍历集合以检查每次触摸的条件,而不仅仅是从集合中获取第一次触摸。

for touch in touches {
  // do something with the touch object
  print(touch.location(mySKNodeObject))
}

除了 Commscheck 的回答外,您还可以通过以下方式检查节点是否位于特定位置:

for _touch in touches {
   let aTouch = _touch.location(in: self)
   if nodes(at: aTouch).contains(desiredNode) {
     print("desired node found")
     desireNode.doSomething()

     // You can also do, 
     // if desiredNode.contains(aTouch) {
   }
}

使用 SKScene.nodes 然后使用 .contains 因为 nodes 是一个数组; SKScene 继承自 SKEffectsNode,SKEffectsNode 继承自 SKNode.. 命令单击顶部的 SKScene,或在导航器中显示 class 层次结构,您可以一直追踪此 nodes 到其起源。 ..

open func nodes(at p: CGPoint) -> [SKNode]

您可以输入 "SKScene",然后输入“.”查看所有成员的列表以及实现它们的正确方法。

此外,如果您通常只需要在一个特定节点上进行操作,您可以子class SKNode(创建您自己的自定义节点),然后覆盖它的touches_方法。

这里有很多很好的答案展示了如何做到这一点:)