而不是使用物理物体检测碰撞,我只是使用enumerateChildNodes检查SKSpriteNodes是否相交。当SKSpriteNodes都是场景的子代时,它对我非常有用,但是当其中一个SKSpriteNodes是孙子代时,它不起作用。我曾尝试在SKSpriteNode的名称之前使用//和/ /来搜索所有的树,但这没有帮助。这是我的代码:
override func didMove(to view: SKView) {
let red = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(10,10))
red.name = "red"
self.addChild(red)
let blue = SKSpriteNode(color: UIColor.blueColor(), size: CGSizeMake(10,10))
blue.name = "blue"
self.addChild(blue)
let green = SKSpriteNode(color: UIColor.greenColor(), size: CGSizeMake(10,10))
green.name = "green"
blue.addChild(green)
}
override func update(_ currentTime: TimeInterval) {
enumerateChildNodes(withName:"red") {node, _ in
let red = node as! SKSpriteNode
if red.frame.intersects((self.childNode(withName:"//blue/green")?.frame)!)
{
red.removeFromParent()
}
}
最佳答案
这里有一些问题,您将需要进行两次枚举,并且需要转换框架。
以下代码应能解决此问题,但我尚未测试准确性:
override func update(_ currentTime: TimeInterval) {
var nodesToDelete = [SKNode]()
enumerateChildNodes(withName:"red") {node, _ in
let red = node as! SKSpriteNode
enumerateChildNodes(withName:"//blue/green") {node, killMe in
let green = node as! SKSpriteNode
let point = green.parent!.convert(green.position, to:red.parent!)
let convertedFrame = CGRect(origin:point:size:green.size)
if red.frame.intersects(convertedFrame){
nodesToDelete.append(red)
killMe.initialize(to: true) //stops enumeration of green
}
}
}
nodesToDelete.forEach{$0.removeFromParent()}
}