KeyHit ( key )
Parameters
| key - scan code of the key to test; see ScanCodes for the full table |
Description
|
Returns how many times a key has been pressed since you last asked. Use it for anything that should fire once per press: jumping, shooting a single shot, opening the map, cycling a weapon, confirming a menu item. Because the result is a count you can treat it as a plain yes/no test - If KeyHit(57) Then Jump() - or read the number if you care that the player mashed the key three times in one frame. Reading the count resets it to zero. That is the point of the command, and also its one trap: only one place in your code should test a given key each frame, or whichever check runs first swallows the press and the second one sees nothing. If two systems need the same key, read it once into a variable and share that. Only real presses count. Windows key auto-repeat is ignored, so holding the key down still counts as a single hit - use KeyDown when you want "still held". Keys are identified by scan code (Escape is 1, Space is 57), and codes outside 1 to 255 always return 0. FlushKeys zeroes every counter at once, which is what you want when a level ends or a cutscene finishes so a stray press from a second ago does not skip the next screen. See also: KeyDown, GetKey, WaitKey, FlushKeys, ScanCodes, MouseHit. |
Example
; KeyHit Example ; -------------- Graphics 640,480,0,2 SetBuffer BackBuffer() ; Load the player ship sprite ship=LoadImage("media/player.bmp") ; One entry per bullet in flight Type bullet Field x,y End Type ang#=0 shots=0 While Not KeyDown(1) Cls ; The ship patrols by itself so there is always motion on screen ang=ang+2 x=320+Sin(ang)*250 ; KeyHit returns how many times the key was PRESSED since the ; last call - holding Space down fires only ONE bullet per press. ; (Compare KeyDown, which stays 1 for as long as the key is held.) hits=KeyHit(57) ; 57 = Space (see the ScanCodes help page) If hits>0 Then b.bullet=New bullet b\x=x b\y=400 shots=shots+hits End If ; Move and draw the bullets For b.bullet=Each bullet b\y=b\y-8 If b\y<-8 Then Delete b Else Rect b\x-1,b\y,3,8,True End If Next DrawImage ship,x-16,404 Text 0,0,"Space: fire (tap it - holding does not autofire) Esc: exit" Text 0,20,"KeyHit(57) presses counted so far: "+shots Flip Wend End
Index