创建新的对象自动添加到数组连续[Javascript]
Javascript game Create new objects automatically to add into an array continuously [javascript]
我是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();
这个函数的作用是在开始时生成一个东西,然后在MINUMUM
和MILLISECONDS
之间随机生成一些东西
直接调用window.setInterval()
:
var allEnemies = [];
window.setInterval(function () {
allEnemies.push(new Enemy(0, 135));
}, 2000);
这将在你的数组中每2秒在相同的位置创建一个新的Enemy
对象(你也可以随机化)。
相关文章:
- 匹配 2D 数组中的连续值
- 创建一个javascript数组(N),该数组由连续的较小整数组成,其和为1000
- 比较数组中的连续元素不会返回任何结果(javascript)
- Lodash:从数组中删除连续的重复项
- AngularJS - 从字符串数组中连续更改文本
- 如何完成缺少(连续)元素的数组|Javascript
- 在数组上连续循环时出现问题
- 对于数组 B 中的每个值,想要查找 A 中的连续值
- 在 javascript 中过滤数组以查找 3 个连续的数字
- 如何在ng重复的情况下同时获取两个连续的数组对象
- Javascript检查数组中的项是否连续
- Javascript数组:如何检查两个连续单词是否相同
- 如何从Javascript数组中选择非连续元素
- 使用javascript替换数组中的连续整数
- 如何在数组javascript中获得连续的空格
- 用正则表达式连续收集单词数组中的任意单词
- 将连续调用的函数中的值保存到数组中
- 创建新的对象自动添加到数组连续[Javascript]
- 检查javascript中数组的连续顺序
- 连续删除数组项目(游戏障碍)