Acting on all sprites from the add new sprite method cocos2d xcode
I am building a game for iphone, I am new to game devolo开发者_如何学Cpment and somewhat new to the language. I have balls that fall from the top of the screen to the bottom and the player is supposed to try and catch them. The problem is, I add the new sprites with an "addnewBallSprite" method, and later act on the position in my UpdateEveryFrame method. But if there is still a ball on the screen when a new ball is created the old ball stops moving. Is there a way I can make my change in position command control all instances of the ball sprite??? Please explain in detail. Below is my addNewBall method:
-(void) addNewBall {
int RandomXPosition = (arc4random() % 240) + 40;
int RandomBallSprite = (arc4random() % 5);
NSString *BallFileString = @"OrangeBall.png";
switch (arc4random() % 5) {
case 1:
BallFileString = @"OrangeBall.png";
break;
case 2:
BallFileString = @"GreenBall.png";
break;
case 3:
BallFileString = @"YellowBall.png";
break;
case 4:
BallFileString = @"PinkBall.png";
break;
case 0:
BallFileString = @"BlueBall.png";
break;
}
Ball = [CCSprite spriteWithFile:BallFileString];
Ball.position = ccp(RandomXPosition, 520);
[self addChild:Ball z:1];
}
If you want to run some action (i mean CCAction
or something other if you want) on the sprite you should have a pointer to this sprite. So you can create an NSMutableArray
to keep those pointers and then to interact with them. If the only children of you CCLayer
are balls - you can take there pointers via calling children
method on your CCLayer.
EDIT
If you have many balls the only way to interact with them is to keep their pointers. Add this declaration to your class:
NSMutableArray *ballArray_;
Initialize array in your class init method:
ballArray_ = [[NSMutableArray alloc] init];
When you create a new ball add the ball to the array:
[ballArray addObject:myNewBall];
And now in your update method you can have the access to each ball in your scene:
for (Ball *ball in ballArray)
{
//increase the position of the ball
}
When the ball is catched by User or out of the scene remove it from array:
[ballArray removeObject: someBall];
精彩评论