2

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

Just an example:

https://i.stack.imgur.com/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))
            }
MrrOak
  • 47
  • 3

2 Answers2

0

I think the simplest approach may be to detect a touch on the whole node. Once you get the location of the touch, check if that location is within the area you want. For example if the area is bound by x from 0 to 30, check if the x of the touch location is between 0 and 30. Do a similar check for y. If both x and y are within the bounds, then the touch occurred in the area you want, and then you can perform the action you need.

Hope this helps!

JohnV
  • 981
  • 2
  • 8
  • 18
0

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.

Kamran
  • 14,987
  • 4
  • 33
  • 51