iOS Spritekit intersectsnode does not work for SKShapeNode

906 views Asked by At

I am using the iOS SpriteKit Game Swift template on iOS8.3. I am trying to use the function func intersectsNode(_ node: SKNode) -> Bool to detect overlap of two circles created as SKShapeNodes. Turns out the function does not detect the intersection if its SKShapeNodes. But on further troubleshooting, it turns out the function works if I use the default Spaceship sprite of the template. Here is the code which works:

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")
                }
            }
        }
    }

}

When two sprites overlap in the above code the function returns YES and prints the intersection string. Here is the code which does NOT work:

   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")
                }
            }
        }
    }

}

As you can see the code blocks are completely identical except in one case its an SKSpriteNode and the other case its SKShapeNode. I also printed the frames of the SKShapeNode Circles and I can see they have have valid frames. So I am puzzled by this as I would like to use SKShapeNodes in my code for now but I cannot use the intersectNode function as it does not work.

1

There are 1 answers

1
EmilioPelaez On

The documentation for intersectsNode says this:

The two nodes are considered to intersect if their frames intersect. The children of both nodes are ignored in this test.

Which means you won't get the result you want when using circles.

However, checking if two circles overlap is as easy as checking if the distance between their centers is less than the sum of their radiuses.