How would you splice object?

Subscribe to How would you splice object? 7 posts

avatar for AMD_Paulius_J AMD_Paulius_J 110 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.

 
avatar for BigJM BigJM 468 posts
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.

 
avatar for AMD_Paulius_J AMD_Paulius_J 110 posts
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?

 
avatar for JamesObscura JamesObscura 250 posts
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.

 
avatar for Ace_Blue Ace_Blue 1091 posts
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.

 
avatar for Aesica Aesica 951 posts
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.

 
avatar for AMD_Paulius_J AMD_Paulius_J 110 posts
Flag Post

Thanks a lot!