Use of ‘flags’ with button presses?
-
It’s for button presses in menus and things. I know there’s a thing you can do where you have variables like ‘button previous state’ and ‘button current state’ to prevent unwanted fast repeats, but I haven’t done this for a while and I’ve forgotten how. Would anyone care to jog my memory?
-
@toxibunny I do it a little bit like this:
c = controls(0) lock = [ .a = false ] beep = loadAudio("Gijs de Mik/FX_Bleeps_01") loop c = controls(0) if c.a and !lock.a then lock.a = true playAudio(0,beep,1,0.5,1,0) endif if !c.a then lock.a = false endif repeat
I have used a struct for "lock" as you can put all your buttons in here.
The code above will lock the A button once you have pressed it and play the sound once. When you release A (!c.a) the lock on A is removed.
I've also found it useful to use time() to control repeating actions while the button is held down:
c = controls(0) inputDelay = 0.5 // Half second count = 0 lastInput = [ .up = time() ] loop clear() c = controls(0) if c.up and time() - lastInput.up >= inputDelay then count += 1 lastInput.up = time() endif print(count) update() repeat
The above will give you a counter that increases slowly as you hold the up button down.
-
Thanks, Spt. I put a cooldown timer on my fireballs as a quick hack so they didn’t just all splurge out one per frame, but I knew I needed the thing with flags for other parts of the game. Having a ‘lock’ struct seems like a good idea, thanks!
-
@toxibunny I was just looking for this post and could not find it when searching for "controls". Could you add the tag controls to it?
-
@spt-games I used your lock struct and it works great so far! Thanks very much for the help - Squishy can now get in and out of his speedboat with the same button :D
-
With just one flag needed, something like that struct is very useful but I find that as you add more buttons it gets a bit out of hand.
In my programs I store the entire controls structure at the end of the main loop into an "old" variable. Then you can check the new and old state of any button without the need for a defined struct.
c = controls(0) oldc = c loop clear() c = controls(0) if c.a and !oldc.a then // when A is initially pressed endif oldc = c update() repeat
-
That’s the way I would have done it if I’d remembered how. I like the way spt suggested though. The ’lock’ metaphor is easy to remember.