iOS Spritekit intersectsnode不适用于SKShapeNode

时间:2015-06-12 21:22:53

标签: ios swift sprite-kit skspritenode skshapenode

我在iOS8.3上使用iOS SpriteKit Game Swift模板。我正在尝试使用函数func intersectsNode(_ node: SKNode) -> Bool来检测作为SKShapeNodes创建的两个圆的重叠。事实证明,如果它的SKShapeNodes没有检测到交集。但是在进一步的故障排除中,如果我使用模板的默认Spaceship精灵,那么该功能就可以了。这是有效的代码:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */

    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)

        let sprite = SKSpriteNode(imageNamed:"Spaceship")

         sprite.xScale = 0.3
         sprite.yScale = 0.3
         sprite.position = location

        self.circles.append(sprite)

        self.addChild(sprite)

        if circles.count == 1 {
            println("One circle")
        } else {
            for var index = 0; index < circles.count-1; ++index {
                if sprite.intersectsNode(circles[index]) {
                    println(circles[index].frame)
                    println("Circle intersects another")
                }
            }
        }
    }

}

当两个精灵在上面的代码中重叠时,该函数返回YES并打印交叉字符串。这是不起作用的代码:

   override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */

    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)

        let sprite = SKShapeNode(circleOfRadius: 50)

         sprite.position = location

        self.circles.append(sprite)

        self.addChild(sprite)

        if circles.count == 1 {
            println("One circle")
        } else {
            for var index = 0; index < circles.count-1; ++index {
                if sprite.intersectsNode(circles[index]) {
                    println(circles[index].frame)
                    println("Circle intersects another")
                }
            }
        }
    }

}

正如您所看到的,代码块完全相同,只有一种情况是SKSpriteNode,另一种情况是SKShapeNode。我还打印了SKShapeNode Circles的框架,我可以看到他们有有效的框架。所以我对此感到困惑,因为我现在想在我的代码中使用SKShapeNodes但是我不能使用intersectNode函数,因为它不起作用。

1 个答案:

答案 0 :(得分:1)

intersectsNode的文档说明了这一点:

  

如果两个节点的帧相交,则认为它们相交。在此测试中将忽略两个节点的子节点。

这意味着您在使用圈子时无法获得所需的结果。

然而,检查两个圆是否重叠就像检查它们的中心之间的距离是否小于它们的半径之和一样容易。

相关问题