-1

我在 Xcode 中快速为我的游戏创建了一个健康栏。我将健康栏添加到我的warrior1. 但我想将我的健康栏的颜色更改为黄色,如果healthBar.progress达到 avalue <= 0.5 && progressBar.progress >= 0.2和红色,如果healthBar.progress < 0.2 这是我到目前为止的代码:

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)

那是我的ProgressBar课:

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)
        }
    }
}

有谁知道我必须在 if 和 else 括号中写什么代码?我将不胜感激。

4

1 回答 1

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

            // Set the color
            if value <= 0.2 {
                bar.color = .red
            } else if // Continue on your own
        }
    }
}
于 2019-12-04T12:38:29.747 回答