Javascript:检测碰撞的div

时间:2011-09-27 22:00:10

标签: javascript html geometry collision-detection algebra

如何检测两个div是否重叠?

不考虑div的宽度,它基本上是垂直线段。 (顶部,左侧)点是A点,而底部(顶部+高度)是B点,依此类推。然后我将每个div与divs数组中的其他div进行比较,然后创建一个碰撞div的数组。但是,我仍然坚持如何以编程方式执行此操作。

这是我的div数组:

var divs = [
    {class:'A', top:0,   left:0,   height:'60px'},
    {class:'B', top:50,  left:60,  height:'60px'},
    {class:'C', top:30,  left:10,  height:'60px'},
    {class:'D', top:100, left:180, height:'60px'},
    {class:'E', top:80,  left:50,  height:'60px'},
    {class:'F', top:110, left:200, height:'60px'},
    {class:'G', top:55,  left:80,  height:'60px'}
];

这是我开始的功能:

    this.collide = function( divs )
{
    var collidingDivs = [], z = events.length;

    for(i; i<z; i++)
    {
        if
        (
           // Begin pseudocode
           ( divsB.top >= divsA.top ) && 
           ( (divsB.top + divsB.height) <= (divsA.top + divsA.height) ) 
        )
        {
            collidingDivs.push(divs[i].class);
        }
    }
    console.log(collidingDivs); // Array of divs that overlap (collide)
};

我刚刚完全陷入困境。如何迭代每个div并检查它是否与任何其他div发生冲突?

1 个答案:

答案 0 :(得分:4)

您需要循环遍历每个div,然后与嵌套循环中的每个其他div进行比较。然后使用像你所写的逻辑来比较每个组合。这是一个简单地将重叠的div打印到输出的示例(另请注意,我将height元素更改为具有数值而不是文本,以便其值可用于计算中):

var divs = [
    {class:'A', top:0,   left:0,   height:60},
    {class:'B', top:50,  left:60,  height:60},
    {class:'C', top:30,  left:10,  height:60},
    {class:'D', top:100, left:180, height:60},
    {class:'E', top:80,  left:50,  height:60},
    {class:'F', top:110, left:200, height:60},
    {class:'G', top:55,  left:80,  height:60}
];

for (var i=0; i < divs.length - 1; i++)
    for (var j=i+1; j < divs.length; j++)
    {
        var I=divs[i];
        var J=divs[j];

        if ( (I.top <= J.top && (I.top + I.height) >= J.top) ||
             (J.top <= I.top && (J.top + J.height) >= I.top) )
            document.writeln(
                I.class + " collides with " + J.class + "<br />");
    }

输出:

A collides with B
A collides with C
A collides with G
B collides with C
B collides with D
B collides with E
B collides with F
B collides with G
C collides with E
C collides with G
D collides with E
D collides with F
D collides with G
E collides with F
E collides with G
F collides with G

示例工作代码:http://jsfiddle.net/QUrWM/