Trying to understand keyhit function
#3
You could simply change your loop and correct most of the issue here:

Code: (Select All)
Do
    k = _KeyHit '             set k to _keyhit value
Loop Until k > 0 '              do this until _keyhit is positive
'                             now leave loop with k set at positive value from _keyhit

Before, what you were doing was a check at the start of the loop to see if k was positive.  Without manually resetting it with each pass, it's going to retain the value that it had from the previous pass, which means it would've stayed positive from the last run, and then skipped over that DO UNTIL k > 0 .... LOOP.

A few pointers that I'd stick in this type of example though:

Code: (Select All)
Do
    k = _KeyHit '             set k to _keyhit value
    _LIMIT 60 '         add a limit here so that your CPU doesn't go into an endless loop and run hot while waiting for a keypress
Loop Until k > 0 '              do this until _keyhit is positive
'                             now leave loop with k set at positive value from _keyhit

As in the small code above, ,add in a limit to reduce CPU usage.  Checking for a keyhit 60 times per second is more than enough.  I honestly doubt your OS will report key events at that rate to begin with!  There's no real reason to create an unthrottled loop here, just to eat up CPU cycles and heat up your PC and wrap up resources.

Note 2, I'd also add in a _KEYCLEAR before that final GOTO statement.  SLEEP doesn't clear keyboard buffers, and the various key input commands usually stack keypresses in a buffer.  If an user holds down the "A" key for several seconds, your loop only processes one keyhit out of the buffer with each pass it makes, which will end up with it processing multiple times after the user lets up on the key!  You're very likely to see your program end up developing a backlog of keypresses which it has to clear out from the buffer, causing lag and odd behavior in it.  By adding a _KEYCLEAR manually into your program, you make certain that issue goes away before it ever becomes a problem.  It basically turns the program here into one that is processing *current* key events and not *buffered* key events -- which seems to be what you'd prefer for it to be doing in this type of demo with SLEEP introducing a second long delay to things.
Reply


Messages In This Thread
RE: Trying to understand keyhit function - by SMcNeill - 08-09-2022, 04:45 AM



Users browsing this thread: 1 Guest(s)