Alexis
Alexis

Reputation: 25163

2D Rectangle Collision detection in Android

I have many images that I need to place on a canvas over a long period of time so that they look random. However, I don't want any of the images to overlap with each other. My solution so far is to randomly place the image somewhere on the canvas. If it overlaps I'll generate a new random location to try.

Now the tricky part is to see if where I am about to place the image is going to overlap with another image.

I was going to make a large array of 1's and 0's and manually mark off where I put the images. However, I was wondering if anyone knew of a way to "auto detect" using a method if where I am about to place an image will overlap with an existing image? Or if there is a way to do collision detection using some Android function?

Upvotes: 5

Views: 6306

Answers (2)

slayton
slayton

Reputation: 20319

Checking to see if two rectangles overlap is really simple, just use Rect.intersect()

Check out the Rect docs for more information: http://developer.android.com/reference/android/graphics/Rect.html

Although I would recommend you try something different than what you have described above. In the beginning the probability of a collision will be very low. However as the screen fills up the probability of a collision will rise. This result in a lot of collisions and wasted computational power.

You should use something more efficient, off the top of my head you could try something like this:

  1. Split the screen into a grid of size MxN
  2. Keep a list of all unpopulated grid locations
  3. Pick a random grid location for a new image i
  4. Pick a random width and height for image i
  5. If i intersects a grid location that is already populated or it if goes off the screen shrink it
  6. Draw i
  7. If all grid locations are taken quit, else go to 3

Upvotes: 6

Diamondo25
Diamondo25

Reputation: 769

A simple 2D isinbox function could be:

bool IsInBox(int x1, int y1, int width1, int height1, int x2, int y2, int width2, int height2) {
    int right1 = x1 + width1;
    int right2 = x2 + width2;
    int bottom1 = y1 + height1;
    int bottom2 = y2 + height2;

    // Check if top-left point is in box
    if (x2 >= x1 && x2 <= right1 && y2 >= y2 && y2 <= bottom1) return true;
    // Check if bottom-right point is in box
    if (right2 >= x1 && right2 <= right1 && bottom2 >= y2 && bottom2 <= bottom1) return true;
    return false;
}

Not sure if works though xd

Or you could use Rect.Intersect()

Upvotes: 4

Related Questions