0

在下面的代码中,我怎么能说在一个数组中有 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)];
            }
        }
    }

任何帮助,将不胜感激!!

4

1 回答 1

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;

}
于 2013-03-09T19:32:40.003 回答