我试图使用个人小酒吧制作一个类似于守望先锋的健康栏。所以每个酒吧的健康都是20%。所以会有5个酒吧。第一个酒吧的健康状况为1 - 20%,接下来的比例为21 - 40%等等。但我无法弄明白。这就是我到目前为止所做的:
public static double health = 100;
public static double maxHealth = 100;
//Each bar should only be 20 percent of their health (This one from 80 - 100)
public static double usePercent = maxHealth * 80 / 100;
public static double healthPercent = health / maxHealth * 100;
//Percent of health the bar should be
public static double percentUse = healthPercent - usePercent;
public static void onHealthChange(int newHealth)
{
double newHealthPercent = newHealth / maxHealth * 100;
//Percent of health bar should be after updated health
double newPercentUse = Math.abs(newHealthPercent - usePercent);
//Making sure that their health is high enough for this bar
//Ex: if their health is 80+ it would be on the fifth bar
if(newHealthPercent >= usePercent)
{
//The percentage of the bar that should be used
double percentBar = newPercentUse / percentUse * 100;
//The size of each bar is 25
double size = percentBar * 25 / 100;
}
}
答案 0 :(得分:0)
您可以将其想象如下。给定"增量",每个柱中的健康量,为20:
health / 20
(health - 20) / 20
(health - 40) / 20
(health - 60) / 20
(health - 80) / 20
我们可以概括为:
n
,请找到(health - ((n-1) * increment)) / increment
这很好,但如果当前健康状况为100,则第一个健康栏将获得百分比100 / 20 = 500%
。我们可以通过" clamp"来解决这个问题。价值。我们可以去的最低点是0%(你不能有一个负面填充的健康栏),我们可以达到的最高点是100%(你不能有一个过度填充的健康栏)。我们可以使用Java的Math.min
和Math.max
来实现此目的。
在表示分数时,使用范围0到1而不是0到100通常也更方便。我已经在我的例子中做到了这一点。
我就是这样做的:
private static final int NUM_HEALTH_BARS = 5;
private double health = 35;
private final double maxHealth = 80;
private final HealthBar[] healthBars = /* whatever */;
public void onHealthChange(final int newHealth)
{
this.health = newHealth;
updateHealthBars();
}
private void updateHealthBars()
{
final double increment = maxHealth / NUM_HEALTH_BARS;
for (int i = 1; i <= NUM_HEALTH_BARS; ++i)
{
double howFull = (health - ((i - 1) * increment)) / increment;
howFull = Math.min(howFull, 1.0);
howFull = Math.max(howFull, 0.0);
// howFull is 0 to 1, so times by 100 if you need it as a percentage:
healthBars[i].setFull(howFull * 100);
}
}