How to create a progress bar

I'm trying to create some kind of progress bar.

Currently I'm achieving the result by doing

    gfx.sprite.setBackgroundDrawingCallback(
        function(x,y,width,height)
            gfx.setClipRect(x,y,width,height)

           -- HERE
            gfx.fillRect(5, 215, 144, 20)

            backgroundImage:draw(0,0)
            gfx.clearClipRect()
        end
    )

But I was going to put some text there to like Fuel to represent a fuel gauge.

I assume there is a better way of doing this though.

1 Like

to add an option to the pile (not necessarily saying this is the best way to do it, just how i'm doing it) you can draw an outline using drawRect()and then draw a filled rectangle inside it with fillRect().

in something i'm working on currently (and forgive me for the c code, that's what i'm working with and i'm not familiar with lua) i use this to draw vertical progress bars next to the player sprite to track ammo capacity. this is what it looks like.

to break it down, we first define the offset from the player and the dimensions of the bars themselves. we then get a value for how much of the bar to fill using a remap() function i defined in game_math.h. it's just an inverse lerp fed into a lerp function, which allows you to remap one range of numbers to another (so eg. in my code im remapping the current ammo value which exists in a range from 0-100 to the range of the bar's height which is from 0-20).

then we do a tiny bit of maths to place the bars where we want them to be, and then we do the same bit of maths plus a bit extra for the fill of the bars. most importantly, we add a small offset to the fill's y position so that it looks like the bar fills from bottom to top instead top to bottom.

and as a final step, we just actually draw them! i definitely feel like if you wanted to, you could refactor this all away into a function to easily draw these progress bars wherever you want (and maybe i'll do that in future). hopefully that helps though! but again, this isn't necessarily the way, just a way to do it that i've been using.

Ok great, I think fillRect() and gfx.fillRect are the same thing so it looks like we're both doing something similar. I just had a hunch that "There has to be a better way".

Thank you for the tips though. I'll see if I can do like a hybrid of them both maybe and it'll turn out ok.

1 Like

You can setcliprect on a sprite, too.

Then you can have any kind of drawn image progress bar. Overlay another sprite for an outline or surround.

1 Like

Here's a sample of clipping a sprite to make a progress bar

You can add your own layers with labels like FUEL or ENERGY, perhaps draw those with playdate.graphics.kDrawModeXOR so that the word is visible on any colour background. Have fun!

2 Likes