Search code examples
swiftswift-optionals

xcode: swift optionals for the color of my health bar


I created a health bar for my game in Xcode in swift. I added the health bar to my warrior1. but I wanna change the color of my health bar to yellow, if the healthBar.progress reaches a value <= 0.5 && progressBar.progress >= 0.2 and to red, if healthBar.progress < 0.2 that's my code so far:

var warrior1 = Swordsman(position: CGPoint(x: 20, y: 100))
self.addChild(warrior1)
allUnits.append(warrior1)
var progressBar = ProgressBar(color: SKColor.green, size:CGSize(width:100, height:10))
// progressBar.position = warrior1.position
progressBar.position = CGPoint( x: 3, y: 55)

progressBar.progress = 0.5 // if I change the value, the color has to change too
if (progressBar.progress <= 0.5 && progressBar.progress >= 0.2){
    // WHAT SHOULD I WRITE HERE?
}
else if ( progressBar.progress < 0.2){
    // AND HERE?
}
warrior1.addChild(progressBar)

And that is my ProgressBar class:

import Foundation
import SpriteKit

class ProgressBar:SKNode {
    var background:SKSpriteNode?
    var bar:SKSpriteNode?
    var _progress:CGFloat = 0
    var progress:CGFloat {
        get {
            return _progress
        }
        set {
            let value = max(min(newValue,1.0),0.0)
            if let bar = bar {
                bar.xScale = value
                _progress = value
            }
        }
    }

    convenience init(color:SKColor, size:CGSize) {
        self.init()
        background = SKSpriteNode(color:SKColor.black,size:size)
        bar = SKSpriteNode(color:color,size:size)
        if let bar = bar, let background = background {
            bar.xScale = 0.0
            bar.zPosition = 1.0
            bar.position = CGPoint(x:-size.width/2,y:0)
            bar.anchorPoint = CGPoint(x:0.0,y:0.5)
            addChild(background)
            addChild(bar)
        }
    }
}

Does anyone know what code I have to write in the if and else brackets? I would be very grateful for an answer.


Solution

  • Plenty of ways to do that but this could be one of them:

    var progress: CGFloat {
        get {
            return _progress
        }
        set {
            let value = max(min(newValue,1.0),0.0)
            if let bar = bar {
                bar.xScale = value
                _progress = value
    
                // Set the color
                if value <= 0.2 {
                    bar.color = .red
                } else if // Continue on your own
            }
        }
    }