Search code examples
iosswiftlocationsknode

How to check if the location of a node is included in another one?


I'm trying to check if a node is located into another one : for example a balloon in a big rectangle which is moving. If the balloon is no more in the rectangle, I'd like the balloon to disappear.

I've tried with the did begin contact function but it doesn't work.

Thanks for Your help


Solution

  • Given 2 SKSpriteNode(s) with the same parent

    let spriteA = SKSpriteNode()
    let spriteB = SKSpriteNode()
    
    let parent = SKNode()
    parent.addChild(spriteA)
    parent.addChild(spriteB)
    

    we can check if the position point of spriteA is within the frame (bounding box) of spriteB with this line

    CGRectContainsPoint(spriteB.frame, spriteA.position)
    

    Intersection

    Alternatively we can also check for intersection between the bounding boxes of the sprites writing

    CGRectIntersectsRect(spriteA.frame, spriteB.frame)
    

    When spriteA and spriteB do NOT have the same parent

    Now let's consider this scenario

    let spriteA = SKSpriteNode()
    let spriteB = SKSpriteNode()
    
    let scene = SKScene()
    let parent = SKNode()
    scene.addChild(spriteA)
    scene.addChild(parent)
    parent.addChild(spriteB)
    

    To check whether spriteA.position is inside the spriteB.frame, first of all we must convert the spriteA.position to the spriteB coordinates system.

    let spriteAPositionWithSpriteBCoordindates = spriteA.convertPoint(spriteA.position, toNode: spriteB)
    

    Now we can call the CGRectContainsPoint function

    CGRectContainsPoint(spriteB.frame, spriteAPositionWithSpriteBCoordindates)