Search code examples
swiftxcodesprite-kitskspritenode

Detect touch on specific area of a node in SpriteKit


How can I detect touch on a specific area of a node?

Just an example:

https://i.sstatic.net/8jvFb.png

How can i perform an action only when the bottom left part of the red node is touched(the yellow rectangle)?

This is what i have to perform an action for when any part of the node is touched:

if atPoint(location).name == "bubble"{
                node.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 70))
            }

Solution

  • You can define a rectangle for the yellow area as below,

    let yellowBox = CGRect(x: 0, y: 0, width: 40, height: 40)
    

    You can update the x, y, width and height values to your needs.

    Then you can find the touch location inside any node for a touch as below,

    let touchPoint = touch.location(in: bubbleNode)
    

    Now you can simply check if the touchPoint is inside the yellowBox or not as below,

    if yellowBox.contains(touch) {
       print("Yellow box is touched!")
    }
    

    You can check here for more details on how to get the touchLocation in a node.