How would you splice object?

7 posts

Flag Post

If i have enemy array in main timeline, how would you splice 1 object from this array using function that is inside enemy.as file?

i tried using this:

private function removeSelf():void
		{

			MovieClip(root).enemyList.splice(this);
			
			MovieClip(root).back.collision.removeChild(this);
		}

But it splices entire array. i also tried this:

private function removeSelf():void
		{

			MovieClip(root).enemyList.splice(0, 1);
			
			MovieClip(root).back.collision.removeChild(this);
		}

But this way it doesn’t remove a last enemy alive – 1 enemy remains on the stage and it’s impossible to remove him from array.

 
Flag Post

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#splice()
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#indexOf()

A more efficient way would be to move the last object in the array to the index that the object you want to remove is at. I would also suggest that if you’re doing a lot of splicing, an array is possibly not the bast data structure.

 
Flag Post
Originally posted by BigJM:

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#splice()
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#indexOf()

A more efficient way would be to move the last object in the array to the index that the object you want to remove is at. I would also suggest that if you’re doing a lot of splicing, an array is possibly not the bast data structure.

Could you share your knowledge on how to move the last object in the array to let’s say 0. How to change last index to 0? Hmm and what data structure would be better than array?

 
Flag Post

Linked lists are awesome for entity storage. They have O(1) speed for adding/removal. They’re slower than arrays for random access though.

 
Flag Post
Originally posted by AMD_Paulius_J:

Could you share your knowledge on how to move the last object in the array to let’s say 0. How to change last index to 0? Hmm and what data structure would be better than array?

Removing element at index i of Array a:

a[i] = a[a.length];
a.length--;

hope this helps.

Edit: \/ Ooops… yea, a[a.length – 1] is what you want, Aesica is right.

 
Flag Post

^ This is the best way I’ve found, although you want a[i] = a[a.length - 1]; to avoid going past the last element.

 
Flag Post

Thanks a lot!