1

I need pixel-perfect collision detection for my Android game. I've written some code to detect collision with "normal" bitmaps (not rotated); works fine. However, I don’t get it for rotated bitmaps. Unfortunately, Java doesn’t have a class for rotated rectangles, so I implemented one myself. It holds the position of the four corners in relation to the screen and describes the exact location/layer of its bitmap; called "itemSurface". My plan for solving the detection was to:

  1. Detect intersection of the different itemSurfaces
  2. Calculating the overlapping area
  3. Set these areas in relation to its superior itemSurface/bitmap
  4. Compare each single pixel with the corresponding pixel of the other bitmap

Well, I’m having trouble with the first one and the second one. Does anybody has an idea or got some code? Maybe there is already code in Java/Android libs and I just didn’t find it.

Pablo Claus
  • 5,886
  • 3
  • 29
  • 38

1 Answers1

0

I understand that you want a collision detection between rectangles (rotated in different way). You don't need to calculate the overlapping area. Moreover, comparing every pixel will be ineffective.

Implement a static boolean isCollision function which will tell you is there a collision between one rectangle and another. Before you should take a piece of paper do some geometry to find out the exact formulas. For performance reasons do not wrap a rectangle in some Rectangle class, just use primitive types like doubles etc.

Then (pseudo code):

for (every rectangle a)
  for (every rectangle b)
    if (a != b && isCollision(a, b))
      bounce(a, b)  

This is O(n^2), where n is number of rectangles. There are better algorithms if you need more performance. bounce function changes vectors of moving rectangles so that imitates a collision. If the weight of objects was the same (you can aproximate weight with size of the rectangles), you just need to swap two speed vectors.

To bounce elements correctly you could need to store auxiliary table boolean alreadyBounced[][] to determine which rectangles do not need a change of their vectors after bounce (collision), because they were already bounced.

One more tip:

If you are making a game under Android you have to watch out to not allocate memory during gameplay, because it will faster invoke GC, which takes a long time and slow downs your game. I recommend you watching this video and related. Good luck.

Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
  • The Problem is that I'm using Bitmaps which are partial transparent. That's why I have to compare every pixel to accomplish that the collosion looks real. The overlapping area is necessary to know which pixels of the bitmap must be compared. (Please correct me if there is a more efficient way) Moreover, the exact formulas are my main problem :D . Im already looking for them many hours. I hope that somebody already knows an algorithm. PS: Thanks a lot for your tip :) – user1524194 Jul 13 '12 at 19:31