我创建了一个数组,它根据用户点击的内容存储红色、黄色或绿色(3、2 或 1)。我希望代码在数组中选择一个随机数并在屏幕上显示相应的颜色。然而,当代码运行时,程序总是选择最后输入的颜色并且只显示那个颜色。代码:
-(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 应该是随机选择的颜色,但绝不是。