我正在用 JavaScript 制作一个 2D、自上而下的塞尔达风格网络 rpg 单人游戏。
当玩家(紫色衬衫)走近一只猫时,它会“拯救”它......这基本上从舞台上删除animalContainer
了ContainerOfAnimals
(从而从舞台上删除了animalContainer的BMP),然后将那个animalContainer的id添加到rescuedTotal_Array
......
奇怪的是,在下面的图片中,我能够救援animalContainer2
然后救援......但如果我从to ,它会抛出一个animalContainer1
animalContainer1
animalContainer2
Uncaught TypeError: Cannot read property 'id' of undefined` error.
... 基本上:
工作方式:获取 ID 22,然后到 ID 21 ->>> 我注意到的一件事是 ID 的元素名称不会改变......不知道为什么......所以对于破碎的方式...... . 它甚至可能无法将元素名称animalContainer2
与 ID 相关联?但我不知道 ID 和名称是如何像这样解除关联的..
ID in rescued array...: 22, element name: animalContainer1, rescued array length: 2, elem index pos: 0, index: 0
ID in rescued array...: 21, element name: animalContainer1, rescued array length: 2, elem index pos: 1, index: 0
Broken way - 抛出错误:获取 ID 21,然后下降到 ID 22
ID in rescued array...: 21, element name: animalContainer1, rescued array length: 1, elem index pos: 0, index: 0
1. Uncaught TypeError: Cannot read property 'id' of undefined
代码片段:
function grabIt(NPC_id, index) {
//check if NPCid already exists in array before adding...
if ($.inArray(ContainerOfAnimals.children[index].id, rescuedTotal_Array) == -1) {
rescuedTotal_Array.push(ContainerOfAnimals.children[index].id);
}
if (rescuedTotal_Array.length == 2) {
for (var z = 0; z < rescuedTotal_Array.length; z++) {
console.log("ID in rescued array...: " + rescuedTotal_Array[z] + ", \n element name: " + ContainerOfAnimals.children[index].name + ", rescued array length: " + rescuedTotal_Array.length + ",\n elem index pos: " + z + ",\n index: " + index);
}
}
//when I remove the first added element to rescuedTotalArray... the 2nd element's index assumes first added element's index... (goes from 1 to 0)
console.log(index);
console.log("element removed: " + ContainerOfAnimals.children[index]);
stage.update();
ContainerOfAnimals.removeChild(ContainerOfAnimals.children[index]);
updateHUD();
}
我不知道为什么我在数组中存储元素/从舞台上删除它们的顺序很重要......
编辑:我觉得我可以通过按元素 ID 而不是按索引从 ContainerOfAnimals 中删除元素来解决这个问题……容器对象不提供任何getChildID()
功能……
所以我尝试了:
var childToRemove = document.getElementById(ContainerOfAnimals.children[index]);
console.log(childToRemove);
ContainerOfAnimals.removeChild(childToRemove);
console.log(childToRemove) 给我null
的孩子
但是这样做:console.log(ContainerOfAnimals.children[index].id);
给我 id 21
,这是正确的 id ...