注意:添加随机位置和速度的编辑解决方案。注2:新版本增加了触摸检测。
用一个变量来存储五个 CCSprite?最后,您将只有该变量中的最后一个 CCSprite。
您需要将 CCSprite(s) 存储在 CCArray(或 NSMutableArray)中
在你的头文件.h中试试这个:
@interface xyz : CCLayer {
CCArray *appleArray;
}
@property (nonatomic, retain) CCArray *appleArray;
在您的实现文件 .m 中:
@synthesize appleArray;
- (id) init
{
if( (self=[super init])) {
self.touchEnabled = YES;
// Inicialize CCArray
self.appleArray = [CCArray arrayWithCapacity:5];
for (int i = 0; i < 5; i++) {
CCSprite *Apple = [CCSprite spriteWithFile:@"Apple4.png"];
[self addChild:Apple];
int positionX = arc4random()%450;
int positionY = 768 + arc4random()%1000;
// Store speed
float speed = 150 + arc4random()%400;
Apple.tag = speed;
[Apple setPosition:ccp(positionX, positionY)];
// Add CCSprite into CCArray
[appleArray addObject:Apple];
}
[self scheduleUpdate];
}
return self;
}
- (void) update: (ccTime) dt
{
for (int i = 0; i < 5; i++) {
CCSprite *Apple = ((CCSprite *)[appleArray objectAtIndex:i]);
if (Apple.position.y > -250) {
Apple.position = ccp(Apple.position.x, Apple.position.y - (Apple.tag*dt));
}
}
}
- (void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
for (CCSprite *Apple in self.appleArray)
{
if (CGRectContainsPoint(Apple.boundingBox, location))
{
Apple.visible = NO;
}
}
}