【发布时间】:2014-05-26 21:04:34
【问题描述】:
我正在尝试使用循环同时调用对象方法。 我会用一组同时移动的敌人创建一个游戏。
我创建了一个对象“战士”
function Warrior(x, y) {
// Coordinates x, y
this.x = x;
this.y = y;
this.character = $('<div class="enemy"></div>');
// Inserting the div inside #map
this.character.appendTo('#map');
// assigning x and y parameters
this.character.css({
marginLeft: x + 'px',
marginTop: y + 'px'
});
// walk method that move the div
this.walk = function() {
// Moving div 10px to the right
this.character.css('left', "+=10");
}
}
var enemies = new Array();
enemies[0] = new Warrior(0, 0);
enemies[1] = new Warrior(10, 20);
enemies[2] = new Warrior(60, 80);
for(var i=0;i<enemies.length;i++) {
setInterval(function(){enemies[i].walk()}, 1000);
}
我创建了一个数组“敌人”
我尝试同时调用 walk() 方法
但是什么也没发生。我希望 div 可以同时移动!
谢谢!
【问题讨论】:
-
你在任何敌人身上测试过
walk(),它会移动吗?如果不是,则问题不在循环中。
标签: javascript arrays loops object methods