From 8e4faffe8dd481d39f34c7ab4e3697682363ffe9 Mon Sep 17 00:00:00 2001 From: LoneWolfHT Date: Mon, 18 Oct 2021 09:22:03 -0700 Subject: [PATCH] Make health bars show rough percentage of max hp (#9) --- .luacheckrc | 5 +++++ init.lua | 20 +++++++++++++++----- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/.luacheckrc b/.luacheckrc index 7013d48..1447fe7 100644 --- a/.luacheckrc +++ b/.luacheckrc @@ -21,6 +21,11 @@ stds.minetest = { "copy", }, }, + math = { + fields = { + "round", + }, + } } } diff --git a/init.lua b/init.lua index 8cc1224..e28f652 100644 --- a/init.lua +++ b/init.lua @@ -11,8 +11,10 @@ end -- Localize this functions for better performance, -- as it's called on every step local vector_distance = vector.distance -local min = math.min -local max_breath = minetest.PLAYER_MAX_BREATH_DEFAULT or 11 +local max = { + breath = 11, + hp = 20, +} local mt_5 = minetest.features.object_independent_selectionbox @@ -29,6 +31,14 @@ local function add_gauge(player) end end +-- credit: https://github.com/minetest/minetest/blob/6de8d77e17017cd5cc7b065d42566b6b1cd076cc/builtin/game/statbars.lua#L30-L37 +local function scaleToDefault(player, field) + -- Scale "hp" or "breath" to supported amount + local current = player["get_" .. field](player) + local max_display = math.max(player:get_properties()[field .. "_max"], current) + return math.round(current / max_display * max[field]) +end + minetest.register_entity("gauges:hp_bar", { visual = "sprite", visual_size = {x=1, y=1/16, z=1}, @@ -50,8 +60,8 @@ minetest.register_entity("gauges:hp_bar", { return end - local hp = min(player:get_hp(), 20) - local breath = min(player:get_breath(), max_breath) + local hp = scaleToDefault(player, "hp") + local breath = scaleToDefault(player, "breath") if self.hp ~= hp or self.breath ~= breath then local health_t = "health_"..hp..".png" @@ -61,7 +71,7 @@ minetest.register_entity("gauges:hp_bar", { health_t = "blank.png" end - if breath == max_breath then + if breath == max.breath then breath_t = "blank.png" end