0
votes

I have 4 sprites, every time the game starts it would randomly choose 1 from the 4 sprites to be the main sprite.

How can I do this?

I know I would need to use arc4random

3
This question does not meet the standards of this platform. Please try to find a solution on your own first. If you get stuck post details about what you have tried so far. - Ben-G
If any of the below answers worked for you then could you please accept the same. - SaffronState

3 Answers

1
votes

The easiest way would be -- First name you image (.png) files with some numbers for e.g. sprite1.png, sprite2.png ....

    int rndSprtNum = (arc4random() % 4) + 1;         
    CCSPrite *mainSprite = [CCSprite spriteWithFile:[NSString StringWithFormat:@"sprite%d.png",rndSprtNum]];
    mainSprite.position = ccp(x,y);
    [self addChild:mainSprite];

This way you no need to take a mutable array etc. Hope this helps.

0
votes

First of all you are add all sprite in NSMutableArray as below code.

Allocate Array

NSMutableArray *AryT = [[NSMutableArray alloc]init];

Differnt sprite

CCSprite *torpedoOne1 = [CCSprite spriteWithFile:@"[email protected]"];

CCSprite *torpedoOne2 = [CCSprite spriteWithFile:@"[email protected]"];

CCSprite *torpedoOne3 = [CCSprite spriteWithFile:@"[email protected]"];

Add All This sprite in define Array

[AryT addObject:torpedoOne1];

[AryT addObject:torpedoOne2];

[AryT addObject:torpedoOne3];

Take Random number from array

int RandomIndex = arc4random_uniform(AryT.count);

Randomaly sprite

[self addchild:[AryT objectAtIndesx:RandomIndex]];
0
votes

Here's another approach, in case you don't want to rename your files you can simply put their names in an array:

NSString *names[4] = {@"RedSprite.png", @"GreenSprite.png", @"YellowSprite.png", @"PurpleSprite.png"};

CCSprite *sprite = [CCSprite spriteWithFile:names[arc4random_uniform(4)]];

[self addChild:sprite];