Basically I am trying to make it so that when the user hits a fuel tank the old tank disappears and a new one is spawned in a random location. Right now it's detecting the collision but I can't get rid of the child. It will just add a new fuel tank without getting rid of the old one.
What can I do to remove the old child and generate a new one? removefromparent and removeallchildren is not working(nslog shows "move" s I am definitely getting to that statement after a detected collision)
- (void) fuelGenerate {
//make a fuel tank
for (int j=1; j<2; j++) {
SKSpriteNode *fuel = [SKSpriteNode spriteNodeWithImageNamed:@"fuel.png"];
fuel.position = CGPointMake(arc4random_uniform(self.frame.size.width), arc4random_uniform(self.frame.size.height));
[fuel setScale:0.6];
fuel.zPosition = 1;
fuel.shadowCastBitMask = 1;
fuel.name = @"fuelNode";
fuel.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:fuel.frame.size];
fuel.physicsBody.dynamic = FALSE;
fuel.physicsBody.affectedByGravity = false;
fuel.physicsBody.usesPreciseCollisionDetection = YES;
fuel.physicsBody.categoryBitMask = fuelCategory;
fuel.physicsBody.collisionBitMask = fuelCategory | fireCategory;
fuel.physicsBody.contactTestBitMask = fireCategory;
if (FuelGen == 1) {
[self addChild:fuel];
} else if (FuelGen == 0) {
NSLog(@"Move");
[fuel removeFromParent];
[self addChild:fuel];
FuelGen == 1
}
}
}
Here are some observations:
You your code inside of a loop which only runs once. Why are you doing that?
If you are creating an object, in your case a SKSpriteNode, and want to delete it later on, you will need to keep some kind of reference to it. There are several ways of doing which include creating a property or adding the object to an array.
Your IF statement in its current position does not make any sense. Your code is in the middle of creating a SKSpriteNode but your IF statement only ads the node if FuelGen == 1. IF NOT it tries to remove the node which by itself should throw an error because you have not yet added it.
Lastly, when you are using an IF - ELSE IF statement, you should have an ELSE at the end to catch anything else that did not trigger any of the previous IF statements.
To create a SKSpriteNode property add this code between your import(s) and @implementation.
Now you have a property.
To use a NSMutableArray you would do make the array a property and then do something like this:
Now you have created a sprite and added to your array and have a reference to it.