I'm working on a game that implements a health bar. The health bar is a CCSprite that is 1px by 1px and then resized to the size I need it to be using a method I found here. The bar resizes great using this method but I'd like the change the color of the bar depending on how much health is left. Here's the method I'm using to do the resizing.
-(void) takeDamage:(double)damage {
currentHP -= damage;
if( currentHP > 0) {
double percentage = (double)currentHP/ (double)maxHP;
double width = (self.contentSize.width * (3.0f/4.0f)) * percentage;
if (percentage <= 0.2f) {
CCTexture2D * tex = [[CCTextureCache sharedTextureCache] addImage:@"hp_red.png"];
[bar setTexture:tex];
} else if( percentage <= 0.45f) {
CCTexture2D * tex = [[CCTextureCache sharedTextureCache] addImage:@"hp_yellow.png"];
[bar setTexture:tex];
}
[self resizeSprite:bar toWidth:width toHeight:self.contentSize.height/15];
}
[nums setString:[NSString stringWithFormat:@"%i/%i", currentHP, maxHP]];
}
The texture change I'm doing is something else I got from SO and it changes the sprite's image (to another 1px by 1px image except it's yellow or red instead of green). The problem is that the sprite is only half yellow with the other half being black as shown below.
If you look at the health bar for "Abraxol" you'll see the weird half yellow half black effect I'm talking about.
Not certain, but the weirdness of the yellow fading to black might have something to do with the size of the texture being 1px x 1px and how the image file was generated. Have you tried using a larger, say 10px x 10px image file to see if the effect still exists.
Any reason that you don't use a sprite for the health bar that is the size of the health bar?
In the game All Star Rally, in the pic below, I used multiple sprites for the sprite health bar where the red, green, and yellow bars are behind the health bar outline sprite. I just set the anchorpoint to be on the left side of the sprite and manipulate the scaleX of the sprite to change the length of the health bar from a value of 1.0 down to 0.01 as a minimum scale, then I make the sprite not visible and don't try to scale any smaller than that.
You could layer sprite of different colors and swap their visibility if you want to change the color or texture of the sprite as the health bar shrinks.
If you use a bar that is the size of the actual bar in your game, then you could add interesting gradient or other effects to the sprite.
Another option for changing the color of the sprite would be to use the sprite.color to manipulate the color of the sprite. With the color property you can subtract red, green and blue values of the sprite to tint it. If you start with a white sprite, then you can color it red for example by subtracting all of the green and blue color components in the sprite.color.