Dvole Dvole - 8 months ago 76
Objective-C Question

How to make and correctly update progress bar in cocos2d?

I have a game that uses a progress bar to inform player of level of certain stats of the player. For example hunger, when it starts at zero and slowly adds up to maximum bar. When he eats the hunger reduces.

I tried implementing as progressBar, but it works wrong, as the bar expands both ways, and I need it to grow one side only. Also I had hard time setting the bar, since it uses actions.

Is there an easy way to do it?

I have a class Pet and it has int hunger (0-100). I want the bar to be showing hunger.

hungerBar = [CCSprite spriteWithFile:@"redbar.png"];
CCLabelTTF *hungerLabel = [CCLabelTTF labelWithString:@"Hunger:" fontName:@"Helvetica" fontSize:25];
[hungerLabel setColor:ccc3(255, 255, 255)];

// CGPoint temp = ccp(250, 300);
// hungerBar.position = temp;
// [self addChild:hungerBar];
CGPoint temp2 = ccp(250, 320);
[hungerLabel setPosition:temp2];
[self addChild:hungerLabel];

CCSprite *bar = [CCSprite spriteWithFile:@"redbar.png"];
powerBar= [CCProgressTimer progressWithSprite:bar];
powerBar.type = kCCProgressTimerTypeBar;
powerBar.position = ccp(-30, -10);
powerBar.anchorPoint = ccp(0, 0);
powerBar.percentage = 20; // (0 - 100)
[hungerLabel addChild:powerBar];

Added source.


Before cocos2d 2.0, you should be able to just use CCProgressTimer of type: kCCProgressTimerTypeHorizontalBarLR.

CCProgressTimer* powerBar= [CCProgressTimer progressWithFile:@"fullbar.png"];
powerBar.type = kCCProgressTimerTypeHorizontalBarLR;
powerBar.percentage = 0; // (0 - 100)

To vary your hunger level, simply set the percentage property of your bar.


Ok, with cocos2d 2.0, it seems that such a type is no longer available. To get a left-to-right-bar, you will need to set the new but somewhat confusing midpoint and barChangeRate properties (cocos2D 2.0 documentation link):

CCProgressTimer* powerBar= [CCProgressTimer progressWithSprite:[CCSprite spriteWithFile:@"fullbar.png"]];
powerBar.type = kCCProgressTimerTypeBar;
powerBar.midpoint = ccp(0,0); // starts from left
powerBar.barChangeRate = ccp(1,0); // grow only in the "x"-horizontal direction
powerBar.percentage = 0; // (0 - 100)

See if these helps!