Hello I am trying to create a healthbar that scales in max value based on the users level.
But I am kinda stuck with it because everytime the healthbar ends up in not having the right length based on the users level and it's health. The system works like this: the user starts at level 1 with a health value of 150 and increases 10 everytime the user levels up, the max level that exists is 32.
Now I know this might be possible to do with a loop but I am not sure on how do this correctly:
This is the code for the health bar. The user_level is the users level and I am trying to change the element style based on his health, but at the same time that it would match with the current level of the user.
for (let i = 0; i < user_level.value; i ) {
playerhealthbar.style.width = user_health // Something here but I dont know how to.
}
This is the CSS code if it helps. What happens is that the greenbar should shrink so that the red bar underneath becomes visible.
#playerhealth {
position: absolute;
bottom: 0;
left: 0;
height: 45px;
width: 325px;
background: lightgreen;
}
#playerhealthbar {
position: absolute;
height: 50px;
width: 330px;
border: rgb(255, 255, 255) 3px solid;
border-radius: 3px;
margin-right: 20px;
display: inline-block;
margin-top: 442px;
margin-left: 70px;
background: rgb(158, 31, 31);
}
#playerhealthvalue{
position: absolute;
margin-top: 500px;
margin-left: 220px;
font-size: 30px;
color: black;
}
CodePudding user response:
The complete outerbar stays the same. But the greenbar thats inside the whole frame shrinks in size when the health goes down.
So the first thing you have to calculate is what the current maximum health value is. This is given by currentMaxHealth = 150 10 * (level-1)
.
The percent of the green bar is playerHealth / currentMaxHealth * 100
.
The whole logic can be done with just custom properties calc
and var
.
So the CSS could look like this:
function setCurrentHealth(val) {
let root = document.documentElement;
root.style.setProperty('--curr-health', val);
}
function setUserLevel(level) {
let root = document.documentElement;
root.style.setProperty('--user-level', level);
}
document.querySelector('#level').addEventListener('input', (evt) => {
setUserLevel(evt.target.value)
})
document.querySelector('#health').addEventListener('input', (evt) => {
setCurrentHealth(evt.target.value)
})
:root {
--user-level: 1;
--curr-health: 10;
--base-health-level: 150;
--additional-health-per-level: 10;
}
.current-health {
width: calc(var(--curr-health) / (var(--base-health-level) var(--additional-health-per-level) * (var(--user-level) - 1)) * 100%);
height: 100%;
background-color: green;
}
.health-bar {
border: 1px solid black;
width: 300px;
height: 20px;
}
<div >
<div >
</div>
</div>
Level: <input value="1" id="level"><br>
Health: <input value="10" id="health">