我正在努力完成一个简单的画布游戏。我收到此错误:
未捕获的TypeError:allEnemies.forEach不是函数
为什么我收到此错误?
我在下面展示了我如何宣布所有敌人。根据指示,allEnemies应该是一个对象数组。
我对所有敌人的宣告是错误的还是敌人宣称错误的对象?
这是Enemy的声明,我认为他们正在尝试声明一个对象(我从未见过像这样的对象声明)我认为这是一个IIFE正确吗?
var Enemy = function() {
// 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.
以下是整个app.js文件:
// Enemies our player must avoid
var Enemy = function() {
// 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';
}
// 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.
}
// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}
// Now write your own player class
// This class requires an update(), render() and
// a handleInput() method.
var Player = function() {
// Variables applied to each of our instances go here,
// we've provided one for you to get started
this.sprite = 'images/char-pink-girl.png';
}
// Now instantiate your objects.
// Place all enemy objects in an array called allEnemies
// Place the player object in a variable called player
var allEnemies = [];
allEnemies = Enemy;
var player = Player;
// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keyup', function(e) {
var allowedKeys = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
player.handleInput(allowedKeys[e.keyCode]);
});
这是给我错误类型的代码行:
allEnemies.forEach(function(enemy) {
这是函数声明的其余部分:
function updateEntities(dt) {
allEnemies.forEach(function(enemy) {
enemy.update(dt);
});
player.update();
}
答案 0 :(得分:2)
第1行allEnemies
是一个数组
下一行变为Enemy
。
var allEnemies = [];
allEnemies = Enemy;
Enemy
是一个功能
allEnemies
现在是一个功能。
Function.prototype.forEach是undefined
答案 1 :(得分:2)
问题在这里
allEnemies = Enemy;
您将 allEnemies 声明为数组但是您使用上述语句覆盖了它。现在 allEnemies 是一个简单的函数而不是数组。因此,每个都是未定义的。
要创建一个Enemy对象数组,您应该执行以下操作:
allEnemies.push(Enemy);