gpt4 book ai didi

ios - 使用 IF 语句更改图像

转载 作者:行者123 更新时间:2023-12-01 18:58:33 25 4
gpt4 key购买 nike

我在我的游戏中设置了一个燃料条,但我试图使用 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 的可能值。)

其次,看起来您正在设置 fuelRemaining100在方法的顶部。您需要在 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变化。

您可能想研究 Key-Value Observing,它可以让您在 fuelRemaining 时自动更新燃料 View 。变化。这有点让人头疼,但如果你有很多东西在不断变化,那么管理起来会更容易。

关于ios - 使用 IF 语句更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24726987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com