不清楚您想要什么行为,但一般来说,您可能希望使用触摸身份来跟踪正在发生的事情。
例如,如果您正在处理包含节点的场景中的触摸,并且希望只是在触摸节点时开始动作并在触摸结束时停止动作,那么类似:
// 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 在离开节点后立即放弃活动触摸,因此再次重新打开该触摸不会重新激活。
主要的一点是,跟踪触摸身份为您提供了很大的灵活性,但您必须决定您希望游戏如何反应。