Find SKNodes in a specified area

I would like to be able to do something similar to the nodes(at:) function in SpriteKit. However, for my use case, checking if there are SKNodes at one specific CGPoint is simply too specific.

What I would like to have, is an area, (that I can specify), similar to the nodes(at:) function, where I get back the array of nodes intersecting the specific area.

Is there some function that does this for me? Also, I would prefer not to bring any SpriteKit Physics into this.

1 answer

  • answered 2018-03-20 18:22 Ron Myschuk

    what you are looking for is

    func intersects(_ node: SKNode) -> Bool
    

    Returns a Boolean value that indicates whether this node intersects the specified node. The two nodes are considered to intersect if their frames intersect. The children of both nodes are ignored in this test.

    example...

    //sprite created in Scene editor
    if let locationBox = self.childNode(withName: "locationBox") as? SKSpriteNode {
        self.locationBox = locationBox
    }
    

    or

    //sprite created programmatically 
    let locationBox = SKSpriteNode(color: .red, size: CGSize(width: 300, height: 300))
    locationBox.zPosition = 1
    locationBox.position = CGPoint(x: 100, y: 100)
    addChild(locationBox)
    

    checking for intersects

    for child in children { 
        if locationBox.intersects(child) {
            print("child.name \(child.name)")
        }
    }