Forums

ForumsProgramming Forum

[as3]looping through array & splice

Posted Jun 27, '14 at 10:43am

weirdlike

weirdlike

492 posts

Knight

I normally use this method

for(var i:int = 0; i < 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 > = 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.

 

Posted Jun 28, '14 at 1:04pm

Hectichermit

Hectichermit

1,168 posts

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.

 

Posted Jul 3, '14 at 2:24pm

weirdlike

weirdlike

492 posts

Knight

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.

 
Reply to [as3]looping through array & splice

You must be logged in to post a reply!