Search code examples
androidcanvastouch-eventondraw

Detect Collision of rectangle and hide one of them


I am trying to develop a simple 2D game. In which I have rectangles with multiple timers. I wanted to detect a collision of the rectangle in my custom view. I have used multiple timers for both rectangles. I want one of the rectangle to disappear for some time after the collision. I searched a lot on stack overflow as well as on google but can't find a perfect answer regarding my query. Please help. Thanks in advance.


Solution

  • Collision detection for rectangles is really easy. Basically if there is any overlap with regard to the X,Y ranges then they collided. So just do a rectangle intersect check.

    Most places tend to have Rect and Rectangle classes ( this is RectF.intersect() ).

            return a.left < b.right && b.left < a.right
                && a.top < b.bottom && b.top < a.bottom;
    

    You can get more complex than this especially when speed is an issue. Or when one of the rectangles could have moved through another one during the tick but doesn't intersect on the tick.