0

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.

sathish kumar
  • 141
  • 1
  • 13
Palash Dange
  • 127
  • 2
  • 10

1 Answers1

0

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.

Tatarize
  • 10,238
  • 4
  • 58
  • 64
  • Thanks for help @Tatarize . I will try that out. What about hiding the rectangle for some time. Do you have some idea on that part? – Palash Dange Dec 28 '15 at 03:54
  • Just do it programmatically, I assume they are are objects of a given class don't draw them or do collision detection on them for X ticks. – Tatarize Dec 28 '15 at 07:27
  • I am actually drawing(with canvas in a custom view) them instead of making objects. Is there any disadvantage in doing so? – Palash Dange Dec 29 '15 at 02:57
  • Nah, whatever you're storing the data in. They are objects regardless. Even if you're storing them as a few floats. Just don't draw them for X ticks. Which means you need to know things about the rectangle namely where they are, orientation, color, whether they are drawn or not, and then don't draw them for a set number of ticks. So each tick you just decrement and compare then don't draw it below the given range. Even as a stand alone class you end up doing the same thing, it just makes the code a lot easier. – Tatarize Dec 29 '15 at 19:12
  • Yeah, you're likely going to need a set counter and the various aspects about them, so a stand alone class is best. Then just have the draw routine and collide routine check whether or not some set value is above zero. Then just decrement that each time it ticks. When things collide set it to the value of how long you'd like it to not be drawn (or collided with). Wouldn't be hard to have it have a draw function and hand the object the canvas. – Tatarize Dec 29 '15 at 19:15
  • For the super basic I think I wrote a quick demo once. http://pastebin.com/0q9e5Sm6 – Tatarize Dec 29 '15 at 19:20
  • Thanks @Tatarize for such a beautiful explanation. I understood it quiet well, I will try it that way. – Palash Dange Dec 30 '15 at 06:42