I want to create my own progress bar in Sprite Kit.
I figured I will need to images - one fully empty progress bar and filled progress bar.
I have those images, I pu
Assuming HealthBarNode
is a subclass of SKSpriteNode
with a public property health
that varies between 0.0 and 1.0 and whose parental property texture
is generated from the entire color bar image of width _textureWidth
(a private property), you could do something like this:
- (void)setHealth:(CGFloat)fraction
{
self.health = MIN(MAX(0.0, fraction), 1.0); // clamp health between 0.0 and 1.0
SKTexture *textureFrac = [SKTexture textureWithRect:CGRectMake(0, 0, fraction, 1.0) inTexture:self.texture];
// check docs to understand why you can pass in self.texture as the last parameter every time
self.size = CGSizeMake(fraction * _textureWidth, self.size.height);
self.texture = textureFrac;
}
Setting the health
to a new value will cause the health bar (added as a child to the main scene, say) to get cropped properly.