【发布时间】:2021-05-04 20:54:23
【问题描述】:
在我的 SpriteKit 场景中,我得到了以下设置:
名称为sourceNode 的几个节点是场景的直接子节点。
一个名为targetNode 的节点是另一个名为sectionNode 的节点的子节点,sectionNode 也是scene 的子节点。
self --> sourceNode
self --> sectionNode --> targetNode
当使用touchesMoved方法移动sourceNode时,我将sourceNode的position设置为触摸的当前位置。一旦触摸位置高于targetNode,我想通过匹配它们的位置将sourceNode 捕捉到targetNode。
我的问题:
我似乎无法在两个坐标空间之间正确转换。我尝试了convert(_:from:) 和convert(_:to:) 的不同变体,但都不起作用。我知道convert 期望两个节点都在同一个节点树中,但是由于它们都是场景的后代,它们不被视为同一节点树的一部分吗?
(如果sourceNode 和targetNode 与兄弟在同一坐标系中,则代码只需将targetNode 的位置分配给sourceNode 的位置即可)
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let touchLocation = touch.location(in: self)
let touchedNodes = nodes(at: touchLocation)
guard let sourceNode = touchedNodes.filter({$0.name == "sourceNode"}).first else { return }
if let targetNode = touchedNodes.filter({$0.name == "targetNode"}).first {
// sourceNode.position = targetNode.position <-- works if both have the same parents
sourceNode.position = convert(targetNode.position, to: sourceNode)
} else {
sourceNode.position = touchLocation
}
}
}
【问题讨论】:
-
将源移动到目标的地方,你能不能做类似的事情:sourceNode.removeFromParent(), sectionNode.addChild(sourceNode), sourceNode.position = targetNode.position, sourceNode.removeFromParent, addChild(源节点)
-
简化(来不及编辑上面的):sourceNode.move(toParent: sectionNode), sourceNode.position = targetNode.position, sourceNode.move(toParent: scene)
-
就我而言,实际上效果很好!将其发布为答案,我会接受。不过,我仍然知道一种将坐标空间转换为其他用例的方法。我很好奇这将如何工作。
标签: swift sprite-kit coordinates nodes touchesmoved