Question

I have a game in which I need to present enemies (SKSpriteNodes) which have a flying path from right to left, across the screen. I currently made it like Apple's Adventure game, having two arrays: one of active enemies and one of inactive; both have the capacity of 10. When the game needs to add an enemy (through the update method) it takes one from the inactive array, adds it as a child and puts it in the active array. When the enemy finished it's path along the screen OR when it was destroyed, I take it from the active array, remove it from it's parent, and put it at index 0 of the inactive array.

Code:

Adding the enemy:

enemySN = [_asteroidsInactiveMArray lastObject];
[enemySN removeFromParent];
[_asteroidsInactiveMArray removeLastObject];
[_asteroidsActiveMArray addObject:enemySN];
[self addChild:enemySN];

Removing the enemy:

[enemySN died];
[_aliensActiveMArray removeObject:enemySN];
[_aliensInactiveMArray insertObject:enemySN atIndex:0];

My worries are: for now, 10 enemies are enough for current settings, but if I want to multiply the enemies added on the screen, 10 will not be enough no more.

Should I keep this style and try to modify the size of the arrays when I don't have any left? Should I take another approach and stop using arrays and just initialise enemies as I need them?

Was it helpful?

Solution

This is a case of Premature Optimization.

You don't even know what your problems may be yet - it could be memory usage, it could be the time spent searching the array, adding/removing elements, it could not be any issue at all before you run into fillrate limits that prevent you from drawing more enemies on screen before your algorithm even becomes the slightest bit inefficient.

You may even find that your current approach is slower than recreating sprites, so you change it. But then this new approach becomes a significant issue because it doesn't scale up as well. You can only find out through testing and measuring, but again: premature optimization.

Fix problems you actually have; don't chase "maybes".

As for NSMutableArray size isn't fixed like with C arrays. NSMutableArray will grow dynamically if you add more items to it, and shrink accordingly as you remove items.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top