Search code examples
geometrytouchareatouchscreenontouch

Determine if tap is within circular area


In my app I am currently able to work out whether the user's tap is within a rectangular area simply by checking all of the following conditions are true:

  • Finger X > rectangle X
  • Finger Y > rectangle Y
  • Finger X < rectangle X + rectangle Width
  • Finger Y < rectangle Y + rectangle Height

However, I now have to determine if the user taps within a circular area. Currently I have a circular shape on screen and have resorted to just checking it's bounding rectangle, which works but obviously isn't great.

Any help would be appreciated.


Solution

  • The distance between two points in two dimensions is defined as

     dist = sqrt((x2-x1)^2 + (y2-y1)^2)
    

    To check if your tap point is inside a circle, take the centre of your circle as (x1,y1), and the 'tap location' as (x2,y2), and check if

    sqrt((x2-x1)^2 + (y2-y1)^2) < R
    

    With R being the radius of your circle.

    Edit:

    As John mentioned, from a computational point of view it is more interesting to compare vs R^2, to avoid the sqrt for every tap. So the condition becomes:

    (x2-x1)^2 + (y2-y1)^2 < R^2