[SOLVED] Progress bar tutorial not working

Hello, all
I am using this tutorial for a progress bar to make a health bar. In another project I adapted the code to this:

var ProgressBar = pc.createScript('progressBar');
let health = 100;
let dmgVal = 10
// The entity that shows the fill image 
ProgressBar.attributes.add('progressImage', {type: 'entity'});
// The maximum width of the fill image
ProgressBar.attributes.add('progressImageMaxWidth', {type: 'number'});

ProgressBar.prototype.initialize = function() {
    // use our own rect object to set the size of 
    // the progress bar
    this.imageRect = this.progressImage.element.rect.clone();
    
    // initialize progress to 0
    this.setProgress(0);    
};

// Set progress - value is between 0 and 1
ProgressBar.prototype.setProgress = function (value) {    
    console.log(health)
    // clamp value between 0 and 1
    value = pc.math.clamp(value, 0, 1);
    
    this.progress = value;
    
    // find the desired width of our progress fill image
    var width = pc.math.lerp(0, this.progressImageMaxWidth, value);
    // set the width of the fill image element
    this.progressImage.element.width = width;
    
    // Set the width of the element's rect (rect.z) to be the same
    // value as our 0-1 progress.
    // This is so that the fill image will only show the portion
    // of the texture that is visible
    this.imageRect.copy(this.progressImage.element.rect);
    this.imageRect.z = value;
    // force rect update
    this.progressImage.element.rect = this.imageRect;
};

// Increase or decrease the progress automatically
ProgressBar.prototype.update = function(dt) {
    if(this.app.keyboard.wasPressed(pc.KEY_1)){
        health = health - dmgVal;
        this.setProgress(health);
    };

};

To try to simulate damage. For some reason, the progress bar only shoes completely empty or completely full, even though in the consol the vales do decrease between 0 and 100.

Any help would be appreciated!

I’m not sure, but as far I can see the value is clamped between 0 and 1, so if your value is for example 53 it will probably be clamped to 1, which mean completely full.

Thanks, if didn’t know that’s what it did. I changed the 100 to 0.1 and the dmgVal to 0.01. If you get a second, can you please test it for me, I’m out and about and probably won’t get to test it for a while.
It’s fine if you can’t.
https://playcanvas.com/editor/scene/2102458

I got it to work, thanks for helping!

1 Like