2D rectangle collision detection in Android

I have many images that I need to place on the canvas for a long period of time so that they look random. However, I do not want any images to overlap with each other. My solution so far is to randomly place the image somewhere on the canvas. If it overlaps, I will create a new random location to try.

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

I was going to make a large array of 1 and 0 and manually mark where I put the images. However, I was wondering if anyone knows of a method of "automatic detection" using the method, if I am going to place an image, will it overlap with the existing image? Or, if there is a way to do collision detection using some Android features?

+4
source share
2 answers

To verify that two rectangle overlaps are really simple, just use Rect.intersect()

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

Although I would recommend you try something different from what you described above. At first, the probability of a collision will be very low. However, as the screen fills, the likelihood of a collision will increase. This leads to a lot of collisions and loss of processing power.

You should use something more efficient, from the top of your head you can try something like this:

  • Split screen into grid size MxN
  • Keep a list of all uninhabited grid areas.
  • Choose a random grid location for the new image i
  • Choose an arbitrary width and height for image i
  • If i crosses a grid location that is already filled, or if it is disabled, press
  • Draw i
  • If all grid locations are cleared, go to 3
+5
source

A simple 2D isinbox function can 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 xd works though

Or you can use Rect.Intersect ()

+4
source

Source: https://habr.com/ru/post/1393643/


All Articles