由于您需要多个 Enemies(复数),因此您需要一个管理每个 Enemies 的对象。我已将您的“敌人”代码移动到“敌人”中,因为它代表一个实例。然后创建一个包含几个“敌人”对象的“集合”的“敌人”对象,并对每个对象应用“绘制”和“更新”函数:
var canvas = $("#ContainerCanvas")[0].getContext('2d');
var CanvasWidth = 300;
var CanvasHeight = 300;
var FramePSet = 30;
var frameRunner;
var Enemies = {
collection: [],
draw: function () {
canvas.clearRect(0, 0, CanvasWidth, CanvasHeight);
for (var i = 0; i < this.collection.length; i++){
this.collection[i].draw();
}
},
update: function () {
for (var i = 0; i < this.collection.length; i++){
this.collection[i].update();
}
}
};
var Enemy = function () {
var model = {
x: 25,
y: 25,
width: 20,
height: 30,
speed: 0.5,
color: "#000",
draw: function () {
canvas.fillStyle = this.color;
canvas.fillRect(this.x+1, this.y, this.width, this.height);
},
update: function () {
this.y += this.speed;
}
}
return model;
};
function addEnemy(x, y){
var nextEnemy = new Enemy();
nextEnemy.x = x;
nextEnemy.y = y;
Enemies.collection.push(nextEnemy);
}
$(document).ready(function () {
addEnemy(25, 25);
addEnemy(60, 60);
addEnemy(95, 95);
frameRunner = setInterval(function () {
Enemies.update();
Enemies.draw();
}, 1000 / FramePSet);
});
您可以将其复制并粘贴到小提琴的 js 窗格中。希望有帮助。