arrays - Error on AS3: TypeError: Error #1010: A term is undefined and has no properties -
i'm trying create collision code involving array of bullets , array of zombies. when tried code:
for(var bu:int = 0;bu < bullets.length; bu++){ for(var zo:int = 0;zo < zombiecount.length; zo++){ if(bullets[bu].hittestobject(zombiecount[zo])){ stage.removechild(zombiecount[zo]); zombiecount.splice(zo, 1); stage.removechild(bullets[bu]); bullets.splice(bu, 1); trace("hot hit") } } }
i error message. tried code:
for(var bu:int = 0;bu < bullets.length; bu++){ for(var zo:int = 0;zo < zombiecount.length; zo++){ if(bullets[bu].hittestobject(zombiecount[zo])){ stage.removechild(zombiecount[zo]); if(zombiecount.splice(zo,1)!=null){ zombiecount.splice(zo, 1) } stage.removechild(bullets[bu]); bullets.splice(bu, 1) if(bullets.splice(bu,1)!=null){ bullets.splice(bu, 1) } trace("hot hit") } } }
however, though message doesn't appear, objects(or rather remains?) stops there. if go original code, i'll keep receiving error messages. please help.
most issue because of 2 things:
you're splicing array inside loop iterates on said array forwards.
if you're going this, should iterate backwards doesn't mess index.
for example, let's
zombiecount
has 3 elements. first iterationzo = 0
, let's hit test succeeds, splice array,zombiecount
has 2 elements. next iteration,zo=1
, item used referencedzombiecount[1]
inzombiecount[0]
now. you've ended skipping item.
- you remove bullet, don't break out of inner loop (that loops through zombies) - problem here if more 1 zombie touching bullet, you'll end trying remove bullet multiple times , un-intentionally splicing different bullets out of array. error because @ point index
bu
becomes out of range result of issue.
for exmaple, let's
bullets
array has 2 elements , zombie array has3
elements. first iterationbu
0
, let's hittest succeeds on first zombie in array. splicebullets
, has 1 element. let's second zombie in array passes hittest. splicingbullets
again, except it's second item ends getting spliced. let's third zombie in array passes hitest too, there nothing left inbullets
array, trying splice anyway , remove non-existent object stage.
try instead:
//iterate backwards, if remove item array, it's last item , won't throw off order of array for(var bu:int = bullets.length-1;bu >= 0; bu--){ for(var zo:int = zombiecount.length-1;zo >= 0; zo--){ if (bullets[bu].hittestobject(zombiecount[zo])) { //remove zombie stage.removechild(zombiecount[zo]); zombiecount.splice(zo, 1); //remove bullet stage.removechild(bullets[bu]); bullets.splice(bu, 1); trace("hot hit"); break; //break out of inner loop (through zombies), since bullet has been destroyed } } }
Comments
Post a Comment