随机显示精灵图像

时间:2013-04-15 17:18:42

标签: xcode cocos2d-iphone

嗨,目前我的游戏正在从fl_food.plist加载fl_gfood.png或fl_bfood.png。这很好,但现在我有17种不良食品.png和17种美食.png。我的问题是如何随机显示每组中的17个项目之一?我可以为sprite png文件名做一个通配符吗?请参阅下面的代码评论还有一个建议是,我可以将.plist文件名加载到一个数组中并随机选择一个名称,该怎么做。

@implementation Food

+ (void)loadAssets {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [[FLSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:[AssetHelper getDeviceSpecificFileNameFor:@"fl_food.plist"]];
    });

}

- (id)init {
    self = [super init];
    if (self) {
        self.size                   = CGSizeMake(16 * __HIGHRES_SCALE, 16 * __HIGHRES_SCALE);
        self.offset                 = CGPointMake(8 * __HIGHRES_SCALE, 8 * __HIGHRES_SCALE);
        self.removeAfterCollision   = YES;
        self.collideable            = NO;
        self.score                  = 10;
    }
    return self;
}

- (FLSprite *)sprite {
    if(_sprite == nil) {

        if(self.score < 10) {
            _sprite = [FLSprite spriteWithSpriteFrameName:@"fl_gfood.png"]; // fl_gfood_*.png ... Can I do something like this?
        } else {
            _sprite = [FLSprite spriteWithSpriteFrameName:@"fl_bfood.png"];
        }
    }
    return _sprite;
}

1 个答案:

答案 0 :(得分:1)

我会使用arc4random()和stringByAppendingString

- (FLSprite *)sprite {
    if(_sprite == nil) {
        NSString *disFood;

        disFood = (self.score < 10) ? @"fl_gfood" : @"fl_bfood";

        //random # between 1 - 10
        int randNum  = (arc4random() % 10)+1;

        NSString *formattedName = [NSString stringWithFormat:@"_%i.png",randNum];

        disFood = [disFood stringByAppendingString:formattedName];

        _sprite = [FLSprite spriteWithSpriteFrameName:disFood]; 

        NSLog(disFood);//Logging disFood String;
    }
    return _sprite;
}