【发布时间】:2021-06-16 09:17:25
【问题描述】:
所以我正在尝试使用 html canvas 和 js 制作游戏,并且我在角色/项目中生成,但有时它们会聚集在一起,所以我写了一点 while 循环来不断重新生成它们直到它们之间有一定的差距。但是,每当我插入 while 循环时,游戏/浏览器就会冻结/崩溃。我做错了吗?
我的代码:
let mx = Math.floor(Math.random() * (Math.floor(1536) - Math.ceil(512)) + Math.ceil(512));
let m = new Image;
m.src = "./Mushroom.png";
let bx = Math.floor(Math.random() * (Math.floor(3072) - Math.ceil(512)) + Math.ceil(512));
let b = new Image;
b.src = "./Bee.png";
let cx = Math.floor(Math.random() * (Math.floor(4608) - Math.ceil(512)) + Math.ceil(512));
let c = new Image;
c.src = "./Coin.png";
while (true) {
if (mx - bx < 128 || mx - cx < 128 || bx - mx < 128 || bx - cx < 128 || cx - mx < 128 || cx - bx < 128) {
mx = Math.floor(Math.random() * (Math.floor(1536) - Math.ceil(512)) + Math.ceil(512));
bx = Math.floor(Math.random() * (Math.floor(3072) - Math.ceil(512)) + Math.ceil(512));
cx = Math.floor(Math.random() * (Math.floor(4608) - Math.ceil(512)) + Math.ceil(512));
} else {
break;
};
};
【问题讨论】:
-
在该循环运行时不会发生其他任何事情,因此如果需要数百万次迭代才能到达
else子句并跳出循环,它的行为将与您描述的差不多。 (我还没有完成重要的数学运算来弄清楚达到所有这些条件的几率。) -
Math.floor(1536)或Math.ceil(512)不要做任何事情,你可以写1536和512 -
@RobinZigmond - 按照目前的写法,几率正好是 0。看我的回答。
-
@Vilx- - 谢谢,我现在明白了(在发表评论之前我没有非常仔细地分析
if条件,因为它看起来太像工作了!但现在我看到它确实很明显.)
标签: javascript html canvas html5-canvas