Greetings All,
first post here and so I apologise if I am not using the correct forum. I have been lurking and reading for a while and I hope I have the protocol for posting correctly.
My problem (which I think is a misunderstanding of Objective-C) lies in the use of an NSMutableArray to store sprites which are also attached to a layer as children - fancy that. However when it comes time to remove those sprites from the layer and the array (currently on a button press) it does not work the way I think it should, however I do have a working solution but it just "feels" wrong.
I would like either help or an explanation as to why it works one way and not the other. I am posting my code below.
This is where I spawn sprites and fill the array using a cocos2d scheduled event. Positioning and so forth is irrelevant as this is R&D for the game I am writing rather than exact science.
#define MAX_SHIP_COUNT 5
- (void) tick: (ccTime) dt
{
// lets start accumulating time here
static ccTime accumulatedTime = 0.0;
accumulatedTime += dt;
// spawn a ship on the screen if not at maximum
// and enough time has passed (ccTime is in seconds resolution)
if ( (allShips.count < MAX_SHIP_COUNT) && (accumulatedTime > 0.5) ) {
Sprite *newShip = [Sprite spriteWithFile:@"gameShip01.png"];
newShip.position = ccp(75 * allShips.count + 75 , arc4random()%300);
[allShips addObject:newShip];
[self addChild:[allShips lastObject]];
[newShip autorelease];
accumulatedTime = 0.0;
}
}
And this is where I am having the problem - the comments should explain what I am asking about. I only want to remove one ship so I do not understand why I can't just remove one ship and have to jump through the hoops I am jumping through.
- (void)onSettings:(id)sender
{
NSLog(@"on settings");
[((GUILayer *)[self.parent getChildByTag:200]).label setString:@"Settings Hit"];
MotionLayer *motionLayer = ((MotionLayer *)[self.parent getChildByTag:100]);
if (motionLayer.allShips.count > 0)
{
NSMutableArray *removeShip = [[NSMutableArray alloc] init];
[removeShip addObject:(Sprite *)[motionLayer.allShips objectAtIndex:0]];
//[motionLayer removeChild:[removeShip lastObject] cleanup:YES];
// very strange that I must remove the ships from the layer like this
// completely at a loss as to why
for (Sprite *theSprite in removeShip)
{
[motionLayer removeChild:theSprite cleanup:YES];
}
[motionLayer.allShips removeObjectsInArray:removeShip];
NSLog(@"trying to do this again!!!");
}
}
I have tried all sorts of things and none of them except the code above works. Yes I can walk away and say "it works, do not worry" however it "feels" wrong as I have stated.
Thanks In Advance,
ds.david