我需要在很长一段时间内在画布上放置许多图像,以便它们看起来随机。但是,我不希望任何图像彼此重叠。到目前为止,我的解决方案是将图像随机放置在画布上的某个位置。如果它重叠,我将生成一个新的随机位置来尝试。
现在棘手的部分是看我是否要放置图像与其他图像重叠。
我打算制作1和0的大数组并手动标记放置图像的位置。但是,我想知道是否有人知道使用方法“自动检测”的方法,如果我要放置图像将与现有图像重叠?或者,如果有办法使用某些Android功能进行碰撞检测?
答案 0 :(得分:5)
检查两个矩形是否重叠非常简单,只需使用Rect.intersect()
查看Rect
文档以获取更多信息:
http://developer.android.com/reference/android/graphics/Rect.html
虽然我建议你尝试一些与上述不同的东西。在一开始,碰撞的概率将非常低。然而,当屏幕填满时,碰撞的概率会上升。这导致了大量的碰撞和浪费的计算能力。
你应该使用更高效的东西,我可以试试这样的东西:
MxN
i
i
i
与已填充的网格位置相交,或者如果屏幕关闭则会缩小它i
答案 1 :(得分:4)
简单的2D isinbox功能可以是:
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;
}
不确定是否适用于xd
或者您可以使用Rect.Intersect()