Note that there are some explanatory texts on larger screens.

plurals
  1. POCocos2d Random object from array not being called
    primarykey
    data
    text
    <p>I have created an array which stores either red, yellow, or green (3, 2, or 1) based on what the user hits. I want the code to choose a random number in the array and display the corresponding color on the screen. However, when the code runs, the program always chooses the last entered color and only shows that color. Code:</p> <pre><code>-(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!!"); } } </code></pre> <p>Y should be a randomly chosen color, but it never is.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload