2 mapmapm MapMapM 于 2012.12.26 09:59 提问

cocos2D随机数组无法调用

创建了一个数组,其中包括红黄绿(321)三个颜色,根据用户点击随机选择一个数字,然后在屏幕上显示对应的颜色,然后系统选择最后输入的颜色,但是我写的代码没有实现这样的功能:

-(void)CreateEnemy:(ccTime)dt{
CCSprite *Enemy;
int a;
if (colorArray != nil) {
    a = arc4random()% [colorArray count];
}
int y = [[colorArray objectAtIndex:a] integerValue];
if (y == 1) {
    Enemy = [CCSprite spriteWithFile:@"GreenBall.png"];
    int x = arc4random()%320;
    Enemy.position = ccp(x, 530);
    id action = [CCMoveTo actionWithDuration:3 position:ccp(x, -30)];
    [Enemy runAction:[CCSequence actions:action, [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]];
    [enemyArray addObject:Enemy];
    [self addChild:Enemy z:2 tag:1];
    NSLog(@"Green Enemy Attack!!");
}
else if (y == 2) {
    Enemy = [CCSprite spriteWithFile:@"YellowBall.png"];
    int x = arc4random()%320;
    Enemy.position = ccp(x, 530);
    id action = [CCMoveTo actionWithDuration:3 position:ccp(x, -30)];
    [Enemy runAction:[CCSequence actions:action, [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]];
    [enemyArray addObject:Enemy];
    [self addChild:Enemy z:2 tag:1];
    NSLog(@"Yellow Enemy Attack!!");
}
else if (y == 3) {
    Enemy = [CCSprite spriteWithFile:@"RedBall.png"];
    int x = arc4random()%320;
    Enemy.position = ccp(x, 530);
    id action = [CCMoveTo actionWithDuration:3 position:ccp(x, -30)];
    [Enemy runAction:[CCSequence actions:action, [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]];
    [enemyArray addObject:Enemy];
    [self addChild:Enemy z:2 tag:1];
    NSLog(@"Red Enemy Attack!!");
}
}

其中Y是一个随机选择数。

1个回答

abcdeFGh_xyz
abcdeFGh_xyz   2012.12.26 10:54
已采纳

在这段代码中

if (colorArray != nil) {
   a = arc4random()% [colorArray count];
}
int y = [[colorArray objectAtIndex:a] integerValue];

[colorArray count]很有可能没有你需要的值, 因此arc4random只能返回0 (或一组有限的值).

如果你在计算a的值之前加上一个 NSLog跟踪, 就可以估计[colorArray count]的值了.

MapMapM
MapMapM 谢谢~
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!