Search code examples
iosswiftsprite-kitspritetouches

Detect if Touch is Within Sprite Bounds, but Ignore Children


I have a sprite which I need to detect whether a touch has been made within it's bounds. Usually just using the below code works, but my current sprite has children which are outside the bounds of the sprite. Because of this, my touches are detected outside the parent bounds as it seems the sprite bounds include that of it children. Does anybody know how to detect whether a touch is made on the parent only (not the children as well)?

 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    let touch = touches.first as UITouch!
    var touchLocation = touch.locationInNode(self)

    if mySprite.containsPoint(touchLocation) {

        // Do Something

    }

}

Solution

  • Try checking to see if touchLocation is within the frame of mySprite with something like this:

    if CGRectContainsPoint(mySprite.frame, touchLocation) {
      // Do something
    }