ForumsProgramming Forum[as3]looping through array & splice

2 9972
weirdlike
offline
weirdlike
1,299 posts
Prince

I normally use this method

for(var i:int = 0; i &lt array.length; i++)
{
if(array[i].hitTestObject(randomObject)
{
array[i].parent.removeChild(array[i]);
array.splice(i, 1);
i--;
}
}

but I have recently found that you can also do this

for(var i:int = array.length-1; i &gt = 0; i--)
{
if(array[i].hitTestObject(randomObject)
{
array[i].parent.removeChild(array[i]);
array.splice(i, 1);
}
}

What is the method you use the most? and why?
Looping forward or backwards. Or perhaps you have a different method for looping through arrays.

  • 2 Replies
Hectichermit
offline
Hectichermit
1,828 posts
Bard

Assuming you are trying to organize collisions of objects. Would it be more efficient if the object itself could detect its own collision and remove itself from the program? you could use a Static variable to track any child of the class. that way.

If you want speed in this there might be a better data structure then an array.

weirdlike
offline
weirdlike
1,299 posts
Prince

I am doing some code cleanup and optimization, and am trying to find the best method to use.

I currently checking the collision in the game class. I can set it up to have the collision in the child using a static variable which I am already using. But what is most efficient method, I don't know.

I have not taken that route due to the mindset where if 2 children are detecting collision as soon as they collide, whichever is the first that is detecting the collision will be removed while the other will never detect it.

There are different route's to take and I would really like to see a prime example of a working method.

Showing 1-2 of 2