0

I have a game where there is a green circle that spawns randomly at random locations on a scene, and every time the circle is tapped it changes location, with a slight possibility to change to red. When the circle is red, I want the user to tap away screen real estate that is not the red circle. How do I detect a tap not on the circle? My circle is a SKShapeNode. I handle touches with the touchesBegan function.

  • Use this link as reference http://stackoverflow.com/questions/27922198/how-do-i-detect-if-an-skspritenode-has-been-touched – Dieblitzen Dec 09 '15 at 09:56
  • @Dieblitzen `nodeAtPoint` uses a node's frame (i.e., a square in this case) to determine if a user's touch intersects with a node. The method will return the node when the user taps anywhere inside of the frame including regions outside of the circle. – 0x141E Dec 09 '15 at 16:43
  • Oh I thought it only detects if the touch is at that exact point – Dieblitzen Dec 12 '15 at 06:46

1 Answers1

1

To determine if the user's touch is inside or outside of a circle, 1) compute the distance between the touch and the center of the circle and 2) compare if that distance is less than or equal to the radius of the circle. Here's an example of how to do that:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {        
    for touch in touches {
        let location = touch.locationInNode(self)

        let dx = location.x - circle.position.x
        let dy = location.y - circle.position.y

        let distance = sqrt(dx*dx + dy*dy)

        if (distance <= CGFloat(radius)) {
            print ("inside of circle")
        }
        else {
            print ("outside of circle")
        }
    }
}
0x141E
  • 12,613
  • 2
  • 41
  • 54