我已经提供了一种方法,应该适合您的情况。以下是该方法的摘要
- 从一个空碰撞数组开始
- 碰撞数组中的每个元素都将存储与任何矩形相碰撞的矩形数组
- 遍历我们拥有的矩形列表
- 如果矩形不与任何元素相碰撞,则将其附加到碰撞数组中
- 如果矩形仅与一个元素碰撞,则将其附加到该碰撞数组元素中
- 如果矩形与数组中的多个元素碰撞,则将所有这些元素合并为一个,然后删除其余元素
- 最终碰撞数组仅具有碰撞数组元素
- 然后可以计算每个这些碰撞的边界矩形,这只是一个最小/最大问题。
现在来看代码
function doRectsCollide(a, b) {
return !(
((a.top + a.height) < (b.top)) ||
(a.top > (b.top + b.height)) ||
((a.left + a.width) < b.left) ||
(a.left > (b.left + b.width))
);
}
var collisions = [];
var rectangles = [
{left: 74, top: 66.89999389648438, width: 80.5, height: 71},
{left: 111.5, top: 95.89999389648438, width: 125, height: 84},
{left: 177, top: 120.89999389648438, width: 168.5, height: 90},
{left: 93, top: 258.8999938964844, width: 81.5, height: 81},
{left: 265.5, top: 320.8999938964844, width: 92, height: 83},
{left: 393, top: 210.89999389648438, width: 88.5, height: 95}
];
for (rectangle of rectangles) {
var collisions_indexes = [];
index = 0;
for (currentColission of collisions) {
for (rect of currentColission) {
if (doRectsCollide(rect, rectangle) === true) {
collisions_indexes.push(index)
break
}
}
index++;
}
if (collisions_indexes.length == 0) {
collisions.push([rectangle])
} else if (collisions_indexes.length >= 1) {
collisions[collisions_indexes[0]].push(rectangle)
for (var i = 1; i < collisions_indexes.length; i++) {
var new_index = collisions_indexes[i] - (i - 1);
collisions[collisions_indexes[0]].push(...collisions[new_index])
collisions.splice(new_index, 1);
}
}
}
console.log(JSON.stringify(collisions, null, 2));
for (collision of collisions) {
}
现在同样的输出是
[
[
{"left":74,"top":66.89999389648438,"width":80.5,"height":71},
{"left":111.5,"top":95.89999389648438,"width":125,"height":84},
{"left":177,"top":120.89999389648438,"width":168.5,"height":90}
],
[{"left":93,"top":258.8999938964844,"width":81.5,"height":81}],
[{"left":265.5,"top":320.8999938964844,"width":92,"height":83}],
[{"left":393,"top":210.89999389648438,"width":88.5,"height":95}]
]