我有一個數組,它是我正在研究的一個小JS遊戲的一部分,我需要檢查(經常合理)數組中的每個元素都沒有離開「stage」或「遊樂場」,所以我可以刪除它們並保存腳本加載更高效的數字比較
我編碼了下面,並想知道如果有人知道更快/更有效的方式來計算此。這是每50ms運行一次(它處理運動)。
其中bots[i][1]
是X中的移動,而bots[i][2]
是Y中的移動(互斥)。
for (var i in bots) {
var left = parseInt($("#" + i).css("left"));
var top = parseInt($("#" + i).css("top"));
var nextleft = left + bots[i][1];
var nexttop = top + bots[i][2];
if(bots[i][1]>0&&nextleft>=PLAYGROUND_WIDTH) { remove_bot(i); }
else if(bots[i][1]<0&&nextleft<=-GRID_SIZE) { remove_bot(i); }
else if(bots[i][2]>0&&nexttop>=PLAYGROUND_HEIGHT) { remove_bot(i); }
else if(bots[i][2]<0&&nexttop<=-GRID_SIZE) { remove_bot(i); }
else {
//alert(nextleft + ":" + nexttop);
$("#" + i).css("left", ""+(nextleft)+"px");
$("#" + i).css("top", ""+(nexttop)+"px");
}
}
在類似的註釋中,remove_bot(i);功能如下,這是正確的(我無法接合,因爲它改變了元素的所有的ID在數組中。
function remove_bot(i) {
$("#" + i).remove();
bots[i] = false;
}
對於提出的任何建議非常感謝!
真的很有用的建議,我會盡快發佈更新的代碼。不過,我不明白3號你的意思是否可以進一步提醒?非常感謝, – 2010-06-02 16:35:09
@PezCuckow:我已經擴展了我對#3的解釋 – Matt 2010-06-02 16:45:44