gpt4 book ai didi

javascript - 在 Canvas 中随机生成对象,没有重复或重叠

转载 作者:搜寻专家 更新时间:2023-10-31 22:14:52 25 4
gpt4 key购买 nike

如何在 map 上生成对象,而不让它们占据相同的空间或在 HTML5 Canvas 上重叠?

X 坐标在一定程度上是随机生成的。我想检查数组内部以查看它是否已经存在,以及接下来的 20 个值(考虑宽度),但没有运气。

var nrOfPlatforms = 14,
platforms = [],
platformWidth = 20,
platformHeight = 20;
var generatePlatforms = function(){
var positiony = 0, type;
for (var i = 0; i < nrOfPlatforms; i++) {
type = ~~(Math.random()*5);
if (type == 0) type = 1;
else type = 0;
var positionx = (Math.random() * 4000) + 500 - (points/100);
var duplicatetest = 21;
for (var d = 0; d < duplicatetest; d++) {
var duplicate = $(jQuery.inArray((positionx + d), platforms));
if (duplicate > 0) {
var duplicateconfirmed = true;
}
}
if (duplicateconfirmed) {
var positionx = positionx + 20;
}
var duplicateconfirmed = false;
platforms[i] = new Platform(positionx,positiony,type);
}
}();

我最初通过让它们在大约 4000 大的区域中生成来降低几率来进行作弊修复,但我想随着游戏的进行增加难度,通过让它们出现得更多,从而使游戏变得更难。但随后它们重叠了。

以粗略的图片形式,我想要这个

....[]....[].....[]..[]..[][]...

不是这个

......[]...[[]]...[[]]....[]....

我希望这是有道理的。

作为引用,这里是数组检查和难度之前的代码,只是廉价的距离 hack。

var nrOfPlatforms = 14,
platforms = [],
platformWidth = 20,
platformHeight = 20;
var generatePlatforms = function(){
var position = 0, type;
for (var i = 0; i < nrOfPlatforms; i++) {
type = ~~(Math.random()*5);
if (type == 0) type = 1;
else type = 0;
platforms[i] = new Platform((Math.random() * 4000) + 500,position,type);
}
}();

编辑 1

经过一些调试后,duplicate 返回为 [object Object] 而不是索引号,但不确定为什么

编辑 2

问题是对象在数组平台中,而 x 在数组对象中,那么如何再次搜索内部? ,这就是它之前失败的原因。感谢 firebug 和 console.log(platforms);

platforms = [Object { image=img,  x=1128,  y=260,  more...}, Object { image=img,  x=1640,  y=260,  more...} etc

最佳答案

您可以实现一个 while 循环,尝试插入一个对象,如果发生碰撞则静默失败。然后添加一个计数器并在放置了所需数量的成功对象后退出 while 循环。如果对象靠得很近,这个循环可能会运行更长的时间,因此您可能还想给它一个最长的生命周期。或者您可以实现“是否有可能将 z 对象放置在 x 和 y 的 map 上”以防止它永远运行。

这是一个例子(demo):

//Fill an array with 20x20 points at random locations without overlap
var platforms = [],
platformSize = 20,
platformWidth = 200,
platformHeight = 200;

function generatePlatforms(k) {
var placed = 0,
maxAttempts = k*10;
while(placed < k && maxAttempts > 0) {
var x = Math.floor(Math.random()*platformWidth),
y = Math.floor(Math.random()*platformHeight),
available = true;
for(var point in platforms) {
if(Math.abs(point.x-x) < platformSize && Math.abs(point.y-y) < platformSize) {
available = false;
break;
}
}
if(available) {
platforms.push({
x: x,
y: y
});
placed += 1;
}
maxAttempts -= 1;
}
}

generatePlatforms(14);
console.log(platforms);

关于javascript - 在 Canvas 中随机生成对象,没有重复或重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14364161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com