Hey guys ive recently developed a bosses plugin I set the health above the bosses head as $entity->setNameTag("Health: " . $entity->getHealth() . "/" . $entity->getMaxHealth() . " ❤"); but when attacked the health doesn't update or change anybody know how to help me make it change everytime it is attacked?
Here is something I use. PHP: class HealthIndicatorEngine extends Engine { const HEARTH_SYMBOL = "\xE2\x9D\xA4"; const NEW_LINE = "\n"; /** * @param EntityDamageEvent $event * @priority HIGHEST */ public function onDamage(EntityDamageEvent $event) { $e = $event->getEntity(); if($e instanceof Player) { $this->updateNametag($e); } } /** * @param PlayerJoinEvent $event * @priority HIGHEST */ public function onPlayerJoin(PlayerJoinEvent $event) { $this->updateNametag($event->getPlayer()); } public function entityHeal(EntityRegainHealthEvent $event) { if($event->getEntity() instanceof Player) { $this->updateNametag($event->getEntity()); } } public function updateNametag(Player $player) : void { $currentNametag = $player->getNameTag(); if(strpos($currentNametag, self::NEW_LINE) !== false) { $currentNametag = explode(self::NEW_LINE, $currentNametag)[0]; } $health = TextFormat::RED . self::HEARTH_SYMBOL . " " . TextFormat::RESET . floor($player->getHealth()); $player->setNametag($currentNametag . self::NEW_LINE . $health); }}
You can make task. PHP: <?phpnamespace x;use pocketmine\scheduler\Task;use pocketmine\Server;use x\BossEntity; // Import your boss entity file.class HealthTask extends Task { public function onRun(int $currentTick) { foreach(Server::getInstance()->getLevels() as $level) { foreach($level->getEntities() as $entity) { if($entity instanceof BossEntity) { $entity->setNameTag(intval($entity->getHealth()) . "/" . intval($entity->getMaxHealth())); } } } }} And schedule this on onEnable(). PHP: $this->getScheduler()->scheduleRepeatingTask(new HealthTask(), 20);
This code iterates over every single entity in the server just to find one that is the boss, to only change the name tag, every time the task ticks. Quite the burden, no?
In addition to that you could also spawn an actual boss bar like from a wither to display the remaining health and modify it in onDamage or updateNametag