我正在尝试使用HTML CSS Javascript和jQuery在gamejam中创建游戏。
我有一个倒计时,向玩家显示他已经离开多少时间,并且当主角被敌人击中时会失去2秒。
我想做的是找到一种每隔x秒生成敌人的方法,只要计时器没有达到30秒(他赢了)或0秒(他输了)
到目前为止,我使用了两个库,QuintusJS (link here)用于物理和jchavannes的倒计时(link here),试图让它们一起工作。 到目前为止,一切都很好,但我无法设法制作一个如下所示的jQuery循环,
while(currentTime < 30000){ //30s in milliseconds
stage.insert(new Q.Enemy({ x: 700, y: 0 })); //Allows ennemies to be generated by QuintusJS
//TODO : adding a delay between enemies generation
}
因为Quintus创建的画布变得完全空白。我还尝试创建一个函数,将checkCurrentTime
设置为true
,currentTime
不等于0
,但在false
时将其更改为parentId
,但它仍然无效。
我这样做错了吗?如果是这样,我怎样才能设置一个能够正确生成敌人的循环?
答案 0 :(得分:0)
您可以创建一个每N毫秒执行一次操作的循环器。例如:
var looper = function (delay, callImmediately, callback) {
var self = this;
var deferred = $.Deferred();
if (callImmediately) {
callback.call(self);
}
var iv = setInterval(function () {
if (deferred.state() === "resolved" || deferred.state() === "rejected") {
clearInterval(iv);
} else {
callback.call(self);
}
}, delay);
return deferred;
};
然后,您可以随时启动和停止它:
// Every second add a new enemy
var loop = looper(1000, false, function () {
console.log("Adding an enemy");
//stage.insert(new Q.Enemy({ x: 700, y: 0 }));
});
// Handle done and fail
loop.done(function () { console.log("All enemies were added!"); });
loop.fail(function () { console.log("The loop was stopped before all enemies were added!"); });
// Resolve the looper after 30 seconds (calls .done())
setTimeout(loop.resolve, 30000);
// Or if something went wrong you can also reject it (calls .fail())...
setTimeout(loop.reject, 5000);
这是一个小例子:
var player = {
health: 100,
};
// Damage the player every second
var iv = setInterval(function () {
player.health -= Math.floor(Math.random() * 10);
if (player.health <= 0) {
clearInterval(iv);
}
}, 1000);
// Every second add a new enemy
var loop = looper(1000, false, function () {
if (player.health <= 0) {
loop.reject("The player is dead. Stopping.");
} else {
//stage.insert(new Q.Enemy({ x: 700, y: 0 }));
console.log("Inserting an enemy; health is", player.health);
}
});
loop.done(function () { console.log("All enemies were added, and player is still alive!"); });
loop.fail(function (message) { console.log(message) });
// Stop the looper after 30 seconds
setTimeout(loop.resolve, 30000);