在下面的代码中我怎么能说在一个数组中有5个苹果,它们会在它们之间以几秒钟(或随机秒数)逐个落下。每次苹果落下时,阵列变为5-1 = 4然后4-1 = 3等等,当它达到1-1 = 0时,它应该在掉落苹果时停止。
我的.h文件:
@interface xyz : CCLayer {
CCArray *appleArray;
}
@property (nonatomic, retain) CCArray *appleArray;
我的.m文件:
@synthesize appleArray;
-(id) init
{
if( (self=[super init])) {
// Init 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;
[Apple setPosition:ccp(positionX, 768)];
// Add CCSprite into CCArray
[appleArray addObject:Apple];
}
[self scheduleUpdate];
}
return self;
}
-(void) update: (ccTime) dt
{
for (int i = 0; i < 5; i++) {
// Retrieve
CCSprite *Apple = ((CCSprite *)[appleArray objectAtIndex:i]);
Apple.position = ccp(Apple.position.x, Apple.position.y -300*dt);
if (Apple.position.y < -100+64)
{
int positionX = arc4random()% 450; //not 1000
[Apple setPosition:ccp(positionX, 768)];
}
}
}
任何帮助都将不胜感激!!
答案 0 :(得分:1)
确保包含QuartzCore框架并链接到它。
在.h中添加这些实例变量:
int _lastSpawn;
double _mediaTime;
int _mediaTimeInt;
int _lastIndex;
BOOL _randomTimeSet;
int _randomTime;
在.m init方法中添加以下行:
_mediaTime = CACurrentMediaTime();
_lastSpawn = (int)_mediaTime;
将更新方法更改为:
-(void) update: (ccTime) dt
{
// Get Random Time Interval between 0 and 10 seconds.
if(!_randomTimeSet) {
_randomTime = arc4random() % 11;
_randomTimeSet = YES;
}
// Set current time
_mediaTime = CACurrentMediaTime();
_mediaTimeInt = (int)_mediaTime;
// Check to see if enough time has lapsed to spawn a new Apple.
if(_mediaTimeInt < (_lastSpawn + _randomTime)) { return; }
// Check if first apple has been added or last apple has been added.
NSNumber *num = [NSNumber numberWithInt:_lastIndex];
if(num == nil) {
_lastIndex = 0;
} else if(num == [appleArray count]-1) {
_lastIndex = 0;
}
CCSprite *Apple = ((CCSprite *)[appleArray objectAtIndex:_lastIndex]);
Apple.position = ccp(Apple.position.x, Apple.position.y -300*dt);
if (Apple.position.y < -100+64)
{
int positionX = arc4random()% 450; //not 1000
[Apple setPosition:ccp(positionX, 768)];
}
_lastIndex += 1;
_randomTimeSet = NO;
_mediaTime = CACurrentMediaTime();
_lastSpawn = (int)_mediaTime;
}