创建新的对象自动添加到数组连续[Javascript]

Javascript game Create new objects automatically to add into an array continuously [javascript]

本文关键字:连续 数组 Javascript 添加 对象 创建      更新时间:2023-09-26

我是Javascript游戏的新手,所以如果这是一个明显的问题,请不要介意。我一直在尝试着创造一款青蛙游戏。对于这个,我有一个对象,我只是想一致地创建新的构造函数,这样它看起来就像一个不断出现的bug。

这是我的敌人对象。

    // Enemies our player must avoid
var Enemy = function(x,y) {
    // Variables applied to each of our instances go here,
    // we've provided one for you to get started
    // The image/sprite for our enemies, this uses
    // a helper we've provided to easily load images
    this.sprite = 'images/enemy-bug.png';
    this.x = x;
    this.y =y;
};
// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    // You should multiply any movement by the dt parameter
    // which will ensure the game runs at the same speed for
    // all computers.
   this.x = this.x+((Math.random() * (15 - 1 + 1) + 1)*dt*35);
   this.y = this.y;
};
// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

然后手动将它们放入数组

    // Place all enemy objects in an array called allEnemies
var allEnemies=[];
allEnemies.push(new Enemy(0,135))
allEnemies.push(new Enemy(0,225))
allEnemies.push(new Enemy(0,50))

我只能看到一列bug。我想让上面的场景自动发生,我想我需要在这里使用调用函数,但我仍然需要在我喜欢的连续间隔内自动执行。

您可以像Joachim说的那样使用window.setInterval(),或者使用window.requestAnimationFrame()甚至使用window.setTimeout()。我个人建议在浏览器中使用requestAnimationFrame(),因为它专门用于绘制动画和渲染,但如果你在节点环境中做一些事情,你应该使用setInterval

除此之外,我看到你将敌人的所有新实例推入一个数组,你可以通过添加一条语句来做到这一点。也可以在创建对象时将其压入数组,如下所示:

var allEnemies = [];
function Enemy(x,y){
    this.x = x || (Math.random() * WIDTH) | 0;
    this.y = y || (Math.random() * height) | 0;
    this.sprite = "bug-sprite-thing";
    allEnemies.push(this); // this is called every time you do `new Enemy(n,n)
    // the new object will automatically be pushed to the array.
}

如果你想随机生成一个新敌人,你可以使用setTimeout

var MINIMUM = 100; // 0.1 seconds
var MILLISECONDS = 10000; // 10 seconds
function spawnAtRandom(){
    // add your code here.
    setTimeout(spawnAtRandom, minimum + (Math.random() * (MILLISECONDS-MINIMUM)));
}
spawnAtRandom();

这个函数的作用是在开始时生成一个东西,然后在MINUMUMMILLISECONDS之间随机生成一些东西

直接调用window.setInterval():

var allEnemies = [];
window.setInterval(function () {
  allEnemies.push(new Enemy(0, 135));
}, 2000);

这将在你的数组中每2秒在相同的位置创建一个新的Enemy对象(你也可以随机化)。