Cocos2d iphone 选择随机精灵COCOS2D3.0

Cocos2d iphone 选择随机精灵COCOS2D3.0,cocos2d-iphone,sprite,Cocos2d Iphone,Sprite,我有4个精灵,每次游戏开始,它都会从4个精灵中随机选择1个作为主精灵 我该怎么做 我知道我需要使用arc4random首先在NSMutableArray中添加所有精灵,如下代码所示 分配数组 NSMutableArray *AryT = [[NSMutableArray alloc]init]; [AryT addObject:torpedoOne1]; [AryT addObject:torpedoOne2]; [AryT addObject:torpedoOne3]; 不同的精灵 C

我有4个精灵,每次游戏开始,它都会从4个精灵中随机选择1个作为主精灵

我该怎么做


我知道我需要使用
arc4random

首先在
NSMutableArray
中添加所有精灵,如下代码所示

分配数组

NSMutableArray *AryT = [[NSMutableArray alloc]init];
[AryT addObject:torpedoOne1];

[AryT addObject:torpedoOne2];

[AryT addObject:torpedoOne3];
不同的精灵

CCSprite *torpedoOne1 = [CCSprite spriteWithFile:@"A@2x.png"];

CCSprite *torpedoOne2 = [CCSprite spriteWithFile:@"B@2x.png"];

CCSprite *torpedoOne3 = [CCSprite spriteWithFile:@"C@2x.png"];
[self addchild:[AryT objectAtIndesx:RandomIndex]];
将所有这些精灵添加到定义数组中

NSMutableArray *AryT = [[NSMutableArray alloc]init];
[AryT addObject:torpedoOne1];

[AryT addObject:torpedoOne2];

[AryT addObject:torpedoOne3];
从数组中获取随机数

int RandomIndex = arc4random_uniform(AryT.count);
随机精灵

CCSprite *torpedoOne1 = [CCSprite spriteWithFile:@"A@2x.png"];

CCSprite *torpedoOne2 = [CCSprite spriteWithFile:@"B@2x.png"];

CCSprite *torpedoOne3 = [CCSprite spriteWithFile:@"C@2x.png"];
[self addchild:[AryT objectAtIndesx:RandomIndex]];
最简单的方法是——用名字命名图像(.png)文件,其中包含一些数字,例如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];

这样您就不需要使用可变数组等。希望这能有所帮助。

这里有另一种方法,如果您不想重命名文件,只需将其名称放入数组即可:

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

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

[self addChild:sprite];

此问题不符合此平台的标准。请先尝试自己寻找解决方案。如果您被卡住,请发布有关您迄今为止尝试过的内容的详细信息。如果以下任何答案对您有效,请您接受相同的答案。请注意,在此实现中,您正在加载所有精灵的纹理数据。如果OP只想在长会话中使用一个,这将导致内存浪费。我建议只在数组中存储文件名,当您选择一个文件名时,加载相应的sprite。