Table of Contents

UI HP bar

In this tutorial, you'll learn how to create a User Interface (UI) in this case, will be an hp bar. We'll do a quick walkthrough of the process step by step, covering the basics of using the CustomUI class and performing simple calculations in Lua. By the end of this guide, you'll be able to implement a functional and visually appealing HP bar in your game.

What you will learn

Effect presentation

Before continuing with the tutorial, let's see the result first.

Explanation of UI components

You can see the order of the components in the image below.

Code and explanation

After taking a look at the code. We will make a quick explanation of the code and its parts. Remember to replace the ids with the ones of your elements.

local CurUi = {
 
    Id = [[7377127869834574121]],
 
    HpBarBg = [[7377127869834574121_1]],
    HpBar = [[7377127869834574121_2]],
    HpBarText = [[7377127869834574121_3]],
 
    HpBarWidth = 445,
    HpBarLength = 80
}
 
function UpdateHpUi(e) 
 
    local playerid = e['eventobjid']
    local playerattr = e['playerattr'] or 2
 
    if playerattr == PLAYERATTR.CUR_HP then 
 
        local _, PlayerHp = Player:getAttr(playerid, PLAYERATTR.CUR_HP)
        local _, PlayerMaxHp = Player:getAttr(playerid, PLAYERATTR.MAX_HP)
 
        local ScaleRatio = (CurUi.HpBarWidth / PlayerMaxHp) * PlayerHp
 
        if PlayerMaxHp <= 0 then PlayerMaxHp = 0 end
 
        Customui:setText(playerid, CurUi.Id, CurUi.HpBarText, math.floor(PlayerHp) .. "/" .. PlayerMaxHp)
        Customui:setSize(playerid, CurUi.Id, CurUi.HpBar, ScaleRatio, CurUi.HpBarLength)
 
    end
 
end
 
ScriptSupportEvent:registerEvent([=[Game.AnyPlayer.EnterGame]=], UpdateHpUi)
ScriptSupportEvent:registerEvent([=[Player.ChangeAttr]=], UpdateHpUi)

After that, we will explain.

The code begins by defining a table named CurUi which stores various the id of all the elements in the HP bar, it stores:

Next, a function named UpdateHpUi is defined. This function will update the HP bar whenever the player's health changes.

Then it calculates the scale that the HP bar must have with the operation

(HpBarWidth / PlayerMaxHp) * PlayerHp

Update HP Text: Sets the text of the HP bar to display the current and maximum HP using Customui:setText(playerid, CurUi.Id, CurUi.HpBarText, math.floor(PlayerHp) .. “/” .. PlayerMaxHp). Update HP Bar Size: Adjusts the size of the HP bar to reflect the player's current health using Customui:setSize(playerid, CurUi.Id, CurUi.HpBar, ScaleRatio, CurUi.HpBarLength). Registering Events

Finally, the script registers the UpdateHpUi function to be called when any player enters the game, or when a player attribute changes, like in this case, the player's health.