Libgdx/Java继承问题

Libgdx/Java继承问题,java,inheritance,libgdx,Java,Inheritance,Libgdx,我目前正在使用libgdx和java进行一个android项目,遇到了一个问题,我不确定我会错在哪里。我有一个扩展小部件的基类。该基类有一个受保护的成员,该成员在每个派生类的act()方法中设置,但基类statBar类在其自己的draw方法中使用该成员。问题是,当调用基类方法时,成员为0,而不应为0。我错过了什么 基类: public abstract class statBar extends Widget { protected Color color; protected Colo

我目前正在使用libgdx和java进行一个android项目,遇到了一个问题,我不确定我会错在哪里。我有一个扩展小部件的基类。该基类有一个受保护的成员,该成员在每个派生类的act()方法中设置,但基类statBar类在其自己的draw方法中使用该成员。问题是,当调用基类方法时,成员为0,而不应为0。我错过了什么

基类:

public abstract class statBar extends Widget {
  protected Color color;
  protected Color darkColor;
  protected Combatant character;

  protected float currentFillWidth;
  private Drawable fullBar;
  privates Drawable emptyBar;

  public statBar(Color color, Combatant character, Skin skin){
    this.character = character;
    this.color = color;
    this.darkColor = color.cpy().mul(0,0,0,.2f);
    this.fullBar = skin.newDrawable("statBar", this.color);
    this.emptyBar = skin.newDrawable("statBar", this.darkColor);
  }

  @Override
  public void draw(Batch batch, float parentAlpha) {
    float x = getX();
    float y = getY();
    float width = getWidth();
    float height = getHeight();

    // draw current fill box
    fullBar.draw(batch, x, y, currentFillWidth, height);

    // if not full, draw empty bar portion
    if (currentFillWidth < width) {
      emptyBar.draw(batch, x+currentFillWidth, y, width-currentFillWidth, height);
    }
  }
}
最后,这就是我如何实例化这个条,它被添加到我屏幕上的一个更大的GUI表中,但实际上其余部分是不相关的

ui.add(new HealthBar(c, skin));

c是玩家队伍中角色的当前迭代。在满hp时,一切都显示良好,但当您的电脑未满时,它会将显示栏清空。调试告诉我这样一个事实:当调用基类draw方法时,currentFillWidth再次为0,而不应该为0。基类方法没有从派生类获取更新的成员值,这一继承缺少什么?当我在ui.draw之前的render方法中调用ui.act时,Libgdx在小部件上调用act。我甚至尝试在派生类中重写draw并强制调用super.draw。同样的结果

从中删除括号

currentFillWidth = getWidth() * (character.getCurHP() / character.getMaxHP());
所以


遗产似乎不错。可能getWidth()或getCurHP()返回0。我有libgdx logcat记录器输出值,通过派生类act方法返回它应该返回的值,正如我所说,当hp满时,它会正确渲染,因此在该点currentFillWidth=width。因此在派生类act方法中,我得到如下输出:bob的hp=35/40,curFill=0。但是当hp满的时候,我得到81…FFS的curFill!我知道了,觉得自己很迟钝。字符的Get方法返回int值,显然不需要对其进行浮点转换,只需在除法之前将返回的int转换为浮点,即可删除小数,问题就解决了。考虑了3个小时,因为假设只要存储的最终值是一个float…currentFillWidth,Java就会一直保留小数直到赋值。你不需要花车,对吧?对于整数,通常先乘后除。在计算中使用整数也稍微有效一些
currentFillWidth = getWidth() * (character.getCurHP() / character.getMaxHP());
currentFillWidth = getWidth() * character.getCurHP() / character.getMaxHP();