Search code examples
androidandroid-touch-event

How to check if a touch event is outside or inside of a region in android


I have an image of a basketball pitch or any other pitch, and I want to check if the user checks outside or inside of 3 points area how can I achieve this? Shall I use predefined points of x,y?

enter image description here


Solution

  • Well if that area is a perfect half-circle, which I think it is, then the formula would be quite easy. You get X and Y coordinates of a touch event whichever way you prefer (that's not the issue here, use GestureDetector for example). I'll just give you an example of the isIn3PointArea() method:

    private boolean isIn3PointArea(float touchX, float touchY, float centerX, float centerY, float r){
        float x = touchX - centerX;
        float y = touchY - centerY;
        return (touchX > centerX && Math.sqrt(x*x+y*y) < r);
    }
    

    Explanation:

    This is the method for the left 3 point area, for the right one you'd just need to swap out > operator with < in the touchX > centerX part. It's quite logical, your point needs to be less than r (which is the radius of your circle) from the center point (which has x coordinate of 0) and y, well whatever you give it, I'm not quite sure what you use to draw the court. Also it needs the touchX to be right of ( greater than > ) the centerX because if it's not, the touch is out of the field. The reverse logic applies to the right 3 point area.

    The only thing that's up to you to deduce is what parameters to give to this method (you didn't share any code so I cannot know what your radius is or what are the coordinates of the court).