【发布时间】:2014-08-06 13:33:33
【问题描述】:
从这个问题开始:
Calculate distance to move a box to remove intersection
我有一个问题,移动一个盒子会导致它与另一个盒子重叠,而目前的算法只会将第一个盒子移回(几乎)它来自的方向,导致它再次与第一个盒子重叠等等。有没有避免这种情况的好方法?我想记住上次的向量,并以某种方式将其与新提议的移动相结合可能是解决方案。
这是一个简单的小提琴:
注意一个盒子是如何移动的,然后与另一个盒子重叠,所以盒子再次向相反方向移动,6个循环后,仍然重叠。
下面是 add 方法的代码 - 它将框添加到列表中,检查当前成员的其他圈数:
self.add = function (item, iteration) {
// check intersections with existing boxes
iteration = iteration || 0;
if (iteration < 6) {
for (var i = 0; i < boxes.length; i++) {
var stationary = boxes[i];
var boundsA = getBounds(item);
var boundsB = getBounds(stationary);
if (doesIntersect(boundsA, boundsB)) {
item.elem.addClass("overlapped");
// move item
// Find vector from mid point of one box to the other
var centerA = {
x: item.x + item.width / 2,
y: item.y + item.height / 2
};
var centerB = {
x: stationary.x + stationary.width / 2,
y: stationary.y + stationary.height / 2
};
var line = {
x1: centerA.x,
y1: centerA.y,
x2: centerB.x,
y2: centerB.y
}
var vector = {
x: Math.min(item.x + item.width, stationary.x + stationary.width) - Math.max(item.x, stationary.x),
y: Math.min(item.y + item.height, stationary.y + stationary.height) - Math.max(item.y, stationary.y)
};
var signX = line.x1 - line.x2 > 0 ? 1 : -1;
var signY = line.y1 - line.y2 > 0 ? 1 : -1;
item.x = item.x + vector.x * signX;
item.y = item.y + vector.y * signY;
item.elem.offset({
left: item.x,
top: item.y
});
return self.add(item, iteration + 1);
}
}
}
boxes.push(item);
}
【问题讨论】:
标签: javascript algorithm layout geometry