【发布时间】:2018-08-31 13:09:19
【问题描述】:
我想生成具有随机尺寸且不会发生冲突的随机矩形。目前我有这个,但它是碰撞,我已经失去了解决这个问题的想法。
<html>
<head>
</head>
<body>
<svg id="svgOne" xmlns="http://www.w3.org/2000/svg" width="550" height="550">
</svg>
<script type="text/javascript">
var svgns = "http://www.w3.org/2000/svg";
function rectan()
{
for (var i = 0; i < 5; i++) {
var x = Math.floor(Math.random() * 200) + 1 ;
y = Math.floor(Math.random() * 200) + 1 ;
var rect = document.createElementNS(svgns, 'rect');
rect.setAttributeNS(null, 'x', x);
rect.setAttributeNS(null, 'y', y);
rect.setAttributeNS(null, 'height', '50');
rect.setAttributeNS(null, 'width', '50');
rect.setAttributeNS(null, 'fill', 'none');
rect.setAttributeNS(null, 'stroke', '#010101');
document.getElementById('svgOne').appendChild(rect);
}
}
rectan();
</script>
</body>
</html>
【问题讨论】:
-
找到一种方法来测试 2 个矩形是否重叠,然后当您生成新的随机矩形时,您可以将它们与现有矩形进行比较,如果有任何重叠,请将其丢弃并重试。你需要一些限制,这样它就不会永远运行:)
-
需要生成多少个随机矩形?
-
我想要多少个循环;)
-
嗯...如果我使用它,那不会像我需要的那样给我矩形:/我需要生成例如 n-矩形:/
标签: javascript html collision-detection collision rectangles