我已经在游戏中设置了加油栏,但是我尝试使用if语句根据加油百分比的低低来更改加油栏图像。由于某些原因,图像不会随百分比变化。因此,栏保持满。这里发生了什么?

fuelRemaining = 100;
    FuelRemaining.text = [NSString stringWithFormat:@"%i%%", fuelRemaining];
    FuelBar.image = [UIImage imageNamed:@"fuel_bar_100.png"];
    if (fuelRemaining > 90) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_100.png"];
    }
    else if (fuelRemaining > 80 && fuelRemaining <= 90) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_90.png"];
    }
    else if (fuelRemaining > 70 && fuelRemaining <= 80) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_80.png"];
    }
    else if (fuelRemaining > 60 && fuelRemaining <= 70) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_70.png"];
    }
    else if (fuelRemaining > 50 && fuelRemaining <= 60) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_60.png"];
    }
    else if (fuelRemaining > 40 && fuelRemaining <= 50) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_50.png"];
    }
    else if (fuelRemaining > 30 && fuelRemaining <= 40) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_40.png"];
    }
    else if (fuelRemaining > 20 && fuelRemaining <= 30) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_30.png"];
    }
    else if (fuelRemaining > 10 && fuelRemaining <= 20) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_20.png"];
    }
    else if (fuelRemaining > 0 && fuelRemaining <= 10) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_10.png"];
    }
    else {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_0.png"];
    }

最佳答案

首先,通过一些基本的数学来简化它:

int fuelRounded = 10.0 * floor((fuelRemaining/10.0)+0.5);
NSString *fuelImageString = [NSString stringWithFormat:@"fuel_bar_%d.png", fuelRounded];
FuelBar.image = [UIImage imageNamed:fuelImageString];

(数学可能需要调整,具体取决于您的游戏逻辑和fuelRemaining的可能值。)

其次,您似乎在方法顶部将fuelRemaining设置为100。在fuelRemaining更改为其他内容后,您需要再次设置图像。

例如:
- (void) updateFuelViews {
    FuelRemaining.text = [NSString stringWithFormat:@"%i%%", fuelRemaining];

    int fuelRounded = 10.0 * floor((fuelRemaining/10.0)+0.5);
    NSString *fuelImageString = [NSString stringWithFormat:@"fuel_bar_%d.png", fuelRounded];
    FuelBar.image = [UIImage imageNamed:fuelImageString];
}

然后,每次[self updateFuelViews];更改时调用fuelRemaining

您可能需要研究“键值观察”,以便在fuelRemaining更改时自动更新燃料视图。这有点令人头疼,但是如果您有很多不断变化的内容,可能会更易于管理。

10-08 12:18