【发布时间】:2021-12-28 17:24:05
【问题描述】:
什么问题导致我的函数 question()(在类 Enemy 中)中 num1 和 num2 的随机化代码无限重复?下面是 question() 中的相关代码,它分别正确生成了 0-30 和 0-15 之间的两个数字,但是是无限的。
num1 = Math.floor(Math.random() * (31 - 0)) + 0;
num2 = Math.floor(Math.random() * (16 - 0)) + 0;
textSize(84);
strokeWeight(1);
fill('#1f7ac4')
text(num1, 200, 170);
text('x', 200, 270);
text(num2, 200, 370);
text('= ???', 200, 470);
下面是运行 question() 的代码,基于玩家对象和敌人 1 之间的简单坐标碰撞检测。
function draw() {
background(220);
image(BG,0,0,width,height);
player.show();
enemy1.show();
collision();
}
function collision() {
if (player.x >= 555 && player.y < 90 && player.x <= 605){
enemy1.question();
}
问题是,当我移动两个对象发生碰撞,并且执行 question() 时,这两行代码带有随机的num1 = Math.floor(Math.random() * (31 - 0)) + 0; num2 = Math.floor(Math.random() * (16 - 0)) + 0;
重复,而不仅仅是一次。我怎样才能让它只为这次碰撞吐出一个数字,然后移除enemy1对象?
谢谢。
【问题讨论】:
-
在类构造函数中生成随机数,而不是在
question()函数中,并将它们保存为对象属性。
标签: javascript math random