【发布时间】:2014-06-22 04:53:03
【问题描述】:
我正在为学校构建一个 Jquery 游戏,我试图通过在函数末尾放置一个 setTimeout() 来让 create() 在运行该方法时重新调用它自己 (我使用 setTimeout 是因为 addEnemySpeed 是随机生成的,因此它每次都会更改)但它不起作用该方法仅从被调用到启动 (smallEnemy.create()) 运行一次但从不回忆自己?我希望这只是我的一个简单的疏忽?在此先感谢您的帮助。 干杯。
// OBSTACLE OBJECT CONSTRUCTOR //
function Obstacle(type, className, speed, startHealth, currentHealth, damageCause) {
this.type = type;
this.className = className;
this.speed = speed;
this.endX = -160;
this.startHealth = startHealth;
this.currentHealth = currentHealth;
this.damageCause = damageCause;
this.create = function(type, endX, speed) {
type = this.type;
endX = this.endX;
speed = this.speed;
var $obstacle = $('<div>');
// if the obstacle is a enemy add enemies class
if (type == 'smallEnemy' || type == 'bigEnemy') {
$obstacle.addClass('enemies');
}
// add correct class name
$obstacle.addClass(type);
// add obstacle to playground
$('#playGround').append($obstacle);
// animate obstacle down x axis remove if hits destination
$obstacle.transition({
x: endX
}, speed, 'linear', function() {
$(this).remove();
});
setTimeout(this.create,addEnemySpeed);
};
}
smallEnemy.create()
【问题讨论】:
-
您希望
this.create重复多少次? -
首先,当
this.create被setTimeout()调用时,this的值将不正确。你可以改用setTimeout(this.create.bind(this), addEnemySpeed)。 -
@AminJafari 我需要它继续不断地调用自己,直到我不再想要它为止。游戏在计时器上运行,并且一个大的 if else-if 语句控制它,例如:假设计时器在 100 到 80 之间,我将以随机速度创建一种类型的障碍物,那么如果计时器在 80 到 60 之间,我将创造另一种类型的障碍等等等等谢谢你的帮助
-
@jfriend00 谢谢!!这正是我想要的。
-
既然您正在学习,您可能想知道如何使用原型、如何使用闭包以及
this是什么:stackoverflow.com/a/16063711/1641941
标签: javascript jquery methods prototype