1

Is there a preferred method for determining if a touch was on a parent or one if it's children in spritekit but still propagate to the parent?

Say I have an SKSpriteNode subclass called "Square" with a 'name' property of "square". In turn this Square also has a child SKLabelNode called "foo" that, in this instance displays something simple like a number.

Now when I tap on a Square or it's label I'd like to update the color of the square.

I know how to do the changing of the colour etc. and handle the tap. But I'm not sure if there's a better way then something like the following:

 //point here is the touch point
  let node = nodes(at: point).first

    if node?.name == "square"  {
          //change color
    }else if node?.parent != nil && node?.parent?.name == "square" {
          //change colour of parent
    }

or is it better to do something like

    //point here is the touch point
  let allnodes = nodes(at: point)

   for node in all nodes {
      if node?.name == "square"  {
          //change color
      }
    }

The second way seems slightly better in that if for some reason I added another child to square I wouldn't have to add another if statement.

For what it's worth I've got a UITapGestureRecognizer on the whole view to determine the point, rather than using the override touchesBegan method etc. This is because I use those methods for scrolling a camera. Not sure if it would make things better to change that logic

TommyBs
  • 9,354
  • 4
  • 34
  • 65
  • When subclassing a SKSpriteNode you can implement its toucesBegan method. Set its userInteractionEnabled to true so it can "absorb" touches... there are already posts here on SO about how to implement this. If you get stuck, let me know. – Whirlwind Jan 09 '17 at 22:41
  • Thanks I did search beforehand but couldn't find anything about what I was specifically trying to achieve. But thanks to your comment I've managed to resolve it. I'll close the question marking it as a duplicate – TommyBs Jan 10 '17 at 10:27
  • Okay, glad to hear you figured it out! – Whirlwind Jan 10 '17 at 10:28
  • Got another question now but it's for a new topic! – TommyBs Jan 10 '17 at 10:29

0 Answers0