如何解決你的代碼,並給你一些性能提示:
這段代碼是非常「蟲友」:要修改陣列的「長度」屬性在依賴於相同屬性的for/in循環中,這實際上不是明智的做法。 的方式我會做:
// Create an array where to store colliding ninjas and shurikens
var depleted:Array = [];
// Create local references to make code more readable and fast (querying arrays all the time is slow).
var ninja:DisplayObject;
var shuriken:DisplayObject;
// Loop in shurikens (no need to check if shurikens have been depleted, since you query only once each of them
for (var q:int=shurikens.length - 1; q >= 0; q--){
shuriken = shurikens[q]; // Assign a shuriken to our variable so you avoid to call further shurikens[q];
for (var w:int=enemy.length - 1; w >= 0; w--){ // Loop in ninjas
ninja = enemy[w]; // Assign ninja
//If the shurikens hit the ninjas. (only if ninjas have not yet been removed)
// This is the core of our improvement, before calling hitTest that is slow, you first check that ninjas have not already been killed
if (depleted.indexOf(ninja) == -1 &&
shuriken.hitTestObject(ninja)){
// It's a hit with a live ninja. I just add both objects to depleted list.
depleted.push(ninja);
depleted.push(shuriken);
break; // Breaking the loop, makes sure shuriken cannot hit 2 ninjas
}
}
}
// Then, you loop in the list of killed ninjas and depleted shurikens, and remove them from arrays and display list
for each (var depletedObj:DisplayObject in depleted) {
// First remove object from the relevant array
if (shurikens.indexOf(depletedObj) != -1) shurikens.splice(shurikens.indexOf(depletedObj), 1); // If it was in the shurikens array remove from there
else if (enemy.indexOf(depletedObj) != -1) enemy.splice(enemy.indexOf(depletedObj), 1); // If it was in the ninjas array remove from there
// The do all necessary stuff to remove object from DisplayList (end eventually add it to an object pooling list)
removeChild(depletedObj);
}
ninjaNum = enemy.length; // Update number of ninjas
另一個提示,如果你對每一幀的循環運行它,如果你把忍者和shurikens在2個不同的DisplayObjectContainer,可以先則hitTest的2個大容器,和一旦碰撞,你可以運行循環來檢查碰撞。另外,在/ in循環的數字中,聲明變量始終爲:int。鍵入變量使訪問速度快於無類型變量。你當然可以改進這個代碼,使其更快,即:爲shurikens和ninjas添加一個「alive = true」屬性,所以你不需要查詢第三個數組等。
你可以用兩個忍者手裏劍 - 檢查如果一個帶有索引「q」的手裏劍同時擊中兩個忍者會發生什麼。你會得到索引'q + 1'拼接出來的手裏劍,而不是從屏幕上移除。爲了解決這個問題,當你發現一個給定的手裏劍時,你需要立即停止外圈。 – Vesper