Wassup,我正在尝试创建一个HTML游戏,但无法弄清楚一点代码。我想不断地随机设置障碍物的间隔,这样几帧之后就没有模式了。
function updateGameArea() {
var x, y, a, b, c, d, e, f, g, h;
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
myGameArea.stop();
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(600)) {
x = myGameArea.canvas.width;
y = myGameArea.canvas.height - 350;
a = myGameArea.canvas.width - -4444;
b = myGameArea.canvas.height - 750;
c = myGameArea.canvas.width - -20674;
d = myGameArea.canvas.height - 750;
e = myGameArea.canvas.width - -11111;
f = myGameArea.canvas.height - 1150;
g = myGameArea.canvas.width - -40678;
h = myGameArea.canvas.height - 1150;
myObstacles.push(new component(500, 300, "green", x, y));
myObstacles.push(new component(500, 300, "green", a, b));
myObstacles.push(new component(500, 300, "green", c, d));
myObstacles.push(new component(500, 300, "green", e, f));
myObstacles.push(new component(500, 300, "green", g, h));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -5;
myObstacles[i].a += -1;
myObstacles[i].c += -1;
myObstacles[i].e += -1;
myObstacles[i].g += -1;
myObstacles[i].update();
}
myScore.text="SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
这是我到目前为止所拥有的。请帮助!!! enter code here
答案 0 :(得分:1)
您可以使用两个函数,一个用于更新/操作,另一个用于使用randome值调用超时。
使用更高级的样式,您可以添加一个检查,以确定下一次超时调用是否应该停止。
function randomTimeout(fn) {
var t = Math.floor(Math.random() * 4 + 2) * 1000;
console.log('randomTimeout', t);
setTimeout(fn, t);
}
function update() {
console.log('update');
randomTimeout(update);
}
update();
答案 1 :(得分:0)
使用Math.random()
。这是来自MDN:
此示例返回指定值之间的随机数。该 返回值不低于(并且可能等于)min,并且是 小于(并且不等于)最大
function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; }