2D矩形碰撞检测的Andr​​oid

问题描述:

我有我需要在画布上放置过的很长一段时间,让他们看起来是随机的许多图像。不过,我不希望任何图像相互重叠。我的解决方案迄今随机放置图像的地方在画布上。如果重叠,我会生成一个新的随机位置尝试。

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.

我要做出一个大阵1和0,并手动标出这里我把图像。不过,我想知道是否有人知道的一种方式为自动检测采用一种方法,如果我在哪里要放置图像将与现有的图像重叠?或者,如果有一种方法使用部分Android功能做碰撞检测?

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?

检查,看看两个矩形重叠非常简单,只需使用 Rect.intersect()

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

查看矩形文档的更多信息:
http://developer.android.com/reference/android/graphics/Rect.html

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. 分割屏幕分成大小的网格的M×N

  2. 将所有无人居住格位置的列表

  3. 挑选一个新的形象随机网格位置我

  4. 选择图像随机的宽度和高度 I

  5. 如果 I 相交一个已经填充网格位置,或者,如果熄灭屏幕缩水

  6. 绘图 I

  7. 如果所有网格位置采取退出,否则转3

  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