所以我一直在努力使用HTML5和JavaScript的遊戲。我試圖製作一個太空侵略者風格的遊戲,結果我有一系列的敵人。我有單獨的功能致力於創建敵人陣列,將它們吸引到屏幕上,移動敵人並最終移除它們。 然而,除去敵人卻是一個問題。這是我的邏輯 如果敵人的健康值小於或等於0,則從陣列中刪除敵人,並將陣列長度縮小1.現在,邏輯將決定如果你開始從敵人身上射擊並殺死敵人,這可能是一場災難數組的開始,因爲數組的長度將會減少,這正是我的問題,如此之低,並注意我的代碼。從陣列中移除元素並避免在javascript中崩潰
function hostile(x, y) {
this.speed = 1;
this.health = 100;
this.x = x;
this.y = y;
this.height = 32;
this.width = 32;
this.isDead = false;
this.direction = 0;
this.deadCount = 0;
this.firing = false;
//this.moving = true;
this.move = function() {
if (this.isDead === false && gameStart === true) {
context.clearRect(0, 0, canvas1.width, canvas1.height);
if (this.x > canvas.width - 64) {
this.y += 10;
this.direction = 0;
}
if (this.x < 0) {
this.y += 10;
}
if (this.direction === 1) {
this.x += this.speed;
} else {
this.x -= this.speed;
}
if (this.x < 0) {
this.direction = 1;
}
if (this.y > 420) {
this.x = 600;
}
}
};
this.draw = function() {
context.drawImage(sprite, 0, 480, 65, 68, this.x, this.y, 65, 65);
};
this.reset = function() {
context.clearRect(this.x, this.y, 65, 65);
this.x = 20;
this.y = 20;
this.health = 100;
};
};
var enemylist = [];
function createEnemies() {
for (var i = 0; i < 6; i++) {
enemylist.push(new hostile(75 * i, 20));
}
};
function deleteEnemy(a) {
enemylist.splice(a);
enemyBulletList.splice(a);
//enemylist.length = enemylist.length-1;
//enemyBulletList.length = enemyBulletList.length - 1;
};
createEnemies();
function moveEnemies() {
for (var i = 0; i < enemylist.length; i++) {
if (enemylist[i].isDead === false && gameStart === true) {
if (enemylist[i].x > canvas.width - 64) {
enemylist[i].y += 10;
enemylist[i].direction = 0;
}
if (enemylist[i].x < 0) {
enemylist[i].y += 10;
}
if (enemylist[i].direction === 1) {
enemylist[i].x += enemylist[i].speed;
} else {
enemylist[i].x -= enemylist[i].speed;
}
if (enemylist[i].x < 0) {
enemylist[i].direction = 1;
}
if (enemylist[i].y > 420) {
enemylist[i].x = 600;
}
}
}
};
因此,爲了解釋我的問題,我可以從陣列中拍攝並殺死敵人,這也會將它們從屏幕上移除。但是如果我從陣列開始射擊敵人,我會讓所有敵人從屏幕上清除,遊戲崩潰。如果您需要更多信息,請隨時詢問。
根據要求,我提交了更多與我的問題有關的代碼。上面的代碼包括敵對功能和與其直接相關的其他功能。
編輯:Vitim.us提供了一個非常有用的提示,關於我的問題,他建議創建一些標誌(var dead = false/true等),並且一旦值被更改,具體實例可以簡單地從屏幕上移開遠離播放器。
嗨Mathletics,謝謝你的建議。我已經在你的代碼中實現了你的建議,而你提供的代碼建議會阻止遊戲崩潰,它不允許我做我想做的事情(一次從陣列中移除1個敵人)如果我殺死了第二個元素數組,然後第二/第三/第四等也被從屏幕上移除。感謝您的額外幫助,並感謝您迄今。 –
你將不得不發佈更多的代碼。在拼接數組時,它將移除已刪除元素後的項目的所有索引。如果您的演示文稿基於這些索引,那麼您將遇到問題。 – Mathletics
如果你只有一個固定數量的實體,那麼你可以將它們標記爲死亡,而不是從數組中刪除,否則你將不得不跟蹤索引。 –