0

固定的

我正在尝试在我的实体名称旁边添加一个健康栏,例如:

3级骷髅||||

哪里的酒吧是多少健康,满分5。我已经尝试了一切似乎,但我无法弄清楚!我觉得它真的很简单,但我就是无法理解......

@EventHandler
public void entityDamageEntity(EntityDamageEvent event) {
    LivingEntity entity = (LivingEntity) event.getEntity();
    if (entity.getCustomName() != null) {
        entity.setCustomName(entity.getCustomName().replaceAll("|", ""));
        int health = (int) Math.ceil(entity.getHealth() / entity.getMaxHealth() * 5);
        int i = 1;
        String healthbar = " |";
        while(i < health){
            i++;
            healthbar = healthbar + "|";
        }
        entity.setCustomName(entity.getCustomName() + healthbar);
    }
}

我似乎无法让它工作!它会做一些奇怪的事情,尝试将它与命名实体一起使用。如果有人能指出错误,那就太好了=D

http://i.stack.imgur.com/RYdcI.png

固定代码:

@EventHandler
public void entityDamageEntity(EntityDamageEvent event) {
    LivingEntity entity = (LivingEntity) event.getEntity();
    if (entity.getCustomName() != null) {
        entity.setCustomName(entity.getCustomName().replaceAll("\\|", ""));
        int health = (int) ((float) entity.getHealth() / entity.getMaxHealth() *5);
        if (health > 0){
            char[] bars = new char[health + 1];
            Arrays.fill(bars, '|');
            entity.setCustomName(entity.getCustomName() + " " + new String(bars));
            entity.setCustomName(entity.getCustomName().replaceAll("  ", " "));
        } else {
            entity.setCustomName(entity.getCustomName()); 
            entity.setCustomName(entity.getCustomName().replaceAll("  ", " "));
        }
    }
}
4

2 回答 2

1

因此,如果不进入游戏,您的代码会遇到 1 个主要问题(您将两个整数相除,这将给您 0),然后是附加字符串的效率问题。修复第一个

int health = (int) ((float) entity.getHealth() / entity.getMaxHealth() *5);

您现在要做的是附加 0 到 5 个生命值条。下面将创建一个 1 到 5 '|' 的数组。它比 while 循环更有效,因为它只是直接创建所需的数组大小,而不是使用追加。

if (health > 0){
    char[] bars = new char[health];
    Arrays.fill(bars, '|');
    entity.setCustomName(entity.getCustomName()+" " + new String(bars));
} else {
    entity.setCustomName(entity.getCustomName()); // no bars to add
}
于 2013-05-03T05:53:24.507 回答
1

我在这里看到了一个直接的问题。|是正则表达式中的一个特殊字符,所以你应该转义这个字符。

尝试:

entity.setCustomName(entity.getCustomName().replaceAll("\\|", ""));
于 2013-05-03T05:47:30.897 回答