我遇到了一个复杂的问题。我试图随着
的条件随机生成不同高度的div我正在创建每个div时存储值。防止重叠很容易,我基本上遍历所有div并检查:
if (obj1.y < obj2.x && obj2.x < obj1.y)
然而,当我有多个碰撞的div时,事情会变得复杂。假设我有两个非碰撞的div(全宽):
这是一个插图的链接(不能包含没有rep的照片:()
https://dl.dropboxusercontent.com/u/23220381/divs.png
Div1.width = Div2.width = Div3.width。
我首次尝试创建算法失败。基本上,当我添加div时,我会检测到有多少碰撞。在Div3的情况下它与其他2个div碰撞,但由于Div1和Div2没有碰撞,我只需要将宽度加倍1/2,而不是1/3。我可以通过检查Div1和Div2是否发生冲突来修复算法,但我不知道如何将其推广到n个Div。
非常感谢任何帮助:)
编辑:添加图片以尝试说明基本情景:)
答案 0 :(得分:0)
我正在使用“查找空盒子”算法,例如:http://www.drdobbs.com/database/the-maximal-rectangle-problem/184410529
步骤1:将屏幕划分为网格,例如
var screenWidth = 1360,
screenHeight = 900;
var unitHeight = 10,
unitWidth = 10;
var X_grids_count = screenWidth/unitWidth;
var Y_grids_count = screenHeight/unitHeight;
步骤2:定义一个二维数组,并将所有网格的值设为0,例如
GridArray = [];
for(i=0;i<X_grids_count;i++)
{
GridArray[i] = [];
for(j=0;j<Y_grids_count;j++)
{
GridArray[i][j] = 0;
}
}
步骤3:当您在屏幕上放置一个对象时,将占用网格的值设为1,例如
//Get the width and length of the object
...
//Get the position of the object
...
//Calculate how many grids in X-coordinate
...
//Calculate how many grids in Y-coordinate
...
//Calculate the start grids
...
//Use a for loop to make the value of the occupied grids into 1
步骤4:当您在屏幕上放置新对象时,扫描所有可用网格(网格值为0)
//Scan from the first grid, check if all grids within the square that the new object occupies are available
...
//Get all available squares in the screen. You can make all startpoints(grids) as candidates
...
//Calculate the best one through all candidates based on your constraints, e.g. the shortest distance
...
//Convert the index of grids to actual pixel and put the object on that position
...
//Set the value of the occupied grids into 1
完成