在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中完成所有触摸,这样每个触摸都可以使用它的位置,或者其它任何东西都可以随身携带。
我知道。愚蠢的问题。我就是那个人。我根本看不出这是怎么做的。
答案 0 :(得分:10)
除非multipleTouchEnabled
属性设置为true
,否则视图通常不会响应多次触摸。
mySprite.multipleTouchEnabled = true
您会注意到方法touchesBegan:event:
不会返回单个UITouch对象,而是返回UITouch对象的Set(也就是无序集合)。
在此方法中,您可以(例如)迭代整个集合,以便在每次触摸时检查条件,而不是仅仅触摸集合。
for touch in touches {
// do something with the touch object
print(touch.location(mySKNodeObject))
}
答案 1 :(得分:2)
此外,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继承自SKNode继承的SKEffectsNode ..命令单击顶部的SKScene,或者在导航器中显示类heirarchy,您可以跟踪此nodes
一直到它的起源......
open func nodes(at p: CGPoint) -> [SKNode]
您可以输入“SKScene”,然后输入“。”查看所有成员的列表以及实施它们的正确方法。
此外,如果您经常需要在一个特定节点上执行操作,则可以继承SKNode(创建自己的自定义节点),然后覆盖其touches_
方法。
这里有很多好的答案,说明如何做到这一点:)