【发布时间】:2022-11-25 04:55:36
【问题描述】:
我有一个名为 Bullet 的类,它本质上是太空入侵者网页上的一个 div。当这颗子弹被“发射”时,我调用了一种逐渐将“子弹”向上移动到屏幕上的方法。
当子弹到达屏幕边缘时,我想从内存中删除整个子弹对象。但是,即使我删除了 setTimeout 循环(我认为),它仍会继续运行。
我相信有更好的方法来做到这一点!也许像这样运行循环是愚蠢的?
TIA
this.bulletmove = new CustomEvent("bulletmove",{detail:this.name});
...
/**
* moves the bullet up the screen gradually
*/
fire(){
var that = this;
setTimeout(function(){
that.moveUp();
window.dispatchEvent(that.bulletmove);
that.fire();
},50);
}
该事件在控制器脚本中拾取,该脚本检查子弹是否已到达屏幕边缘,此时它已被删除:
window.addEventListener('bulletmove', function(evt) {
checkCollision(evt);
},false);
...
/**
*Check if the bullet has gone off screen and deletes it
**/
function checkCollision(e){
var bulletName = e.detail;
var bullet = bullets[bulletName];
//check if the bullet has gone off screen
if (bullet.bottom < 0){
bullet.destroy;
delete bullets[e.detail];
bullet=null;
}
}
【问题讨论】:
-
我认为更好的方法是让游戏循环在
requestAnimationFrame上运行,并根据经过的时间、是否与任何东西发生碰撞等来计算每个刻度的子弹位置。
标签: javascript settimeout