我做了一个简单的游戏(打鼹鼠),游戏的工作原理如下: 每次按下开始按钮,它都会在DOM中放置10个div。 div将随机放入DOM中。
我的问题是它们彼此重叠,有时它们会放在容器外面。
我想知道如何将它们随机放置在容器内而不会相互重叠,我宁愿不使用网格来放置它们,我希望它们随机分布在容器中。
这里是主要功能:
function randomPos(size){
var result = new Array();
var height = (document.getElementById('field').clientHeight);
var width = document.getElementById('field').clientWidth;
for (var i = 0; i < size; i++) {
var obj = {};
var posY = Math.floor(Math.random() * height);
var posX = Math.floor(Math.random() * width);
if (result.length == 0){
obj.x = posX;
obj.y = posY;
result.push(obj);
}
else{
var flag = true;
for (var j = 0; j < i && flag; j++){
if (result[j].y == posY && result[j].x == posX){
flag = false;
}
}
if(flag){
obj.x = posX;
obj.y = posY ;
result.push(obj);
}
else{
i--;
}
}
}
return result;
}
这里是jsfiddle
答案 0 :(得分:1)
这是我修改过的功能 -
function randomPos(size){
var result = new Array();
var height = (document.getElementById('field').clientHeight);
var width = document.getElementById('field').clientWidth;
var generatePos = function(){
// generates the random x and y position, taking into account the size of the object
var posY = Math.floor(Math.random() * (height - 140) + 40);
var posX = Math.floor(Math.random() * (width - 100));
return {x: posX, y: posY}
}
var checkOverlap = function(x, y){
var no_overlap = true
// loops through existing objects and makes sure the newly generated one doesn't overlap
for (var j = 0; j < result.length; j++){
var yDiff = Math.abs(result[j].y - y)
var xDiff = Math.abs(result[j].x - x)
if (yDiff < 100 && xDiff < 100){
no_overlap = false;
}
}
return no_overlap
}
for (var i = 0; i < size; i++) {
var obj = {};
var pos = generatePos()
if (result.length == 0){
obj.x = pos.x;
obj.y = pos.y;
result.push(obj);
}
else{
var no_overlap = checkOverlap(pos.x, pos.y)
if(no_overlap){
obj.x = pos.x;
obj.y = pos.y ;
result.push(obj);
}
else{
i--;
}
}
}
return result;
}