Blitz3D+ Command Reference

KeyDown ( key )

Parameters

key - scan code of the key to test; see ScanCodes for the full table

Description

Returns True while the given key is being held down.

This is the workhorse of game control. Call it every frame inside your main loop and you get the live state of a key: 1 while it is down, 0 while it is up. Holding left to steer, holding a trigger to keep firing, holding shift to sprint - anything where "still pressed" matters is a KeyDown check.

It reads state rather than consuming an event, so as many places in your code as you like can test the same key in the same frame and all of them see it. That is the big difference from KeyHit, which counts fresh presses and clears the count as you read it. Rule of thumb: KeyDown for anything continuous, KeyHit for anything that should happen once per press.

Keys are identified by scan code, not by letter, so the value does not change with the keyboard layout. Scan code 1 is Escape, which is why nearly every Blitz loop is written as While Not KeyDown(1). Only codes 1 to 255 exist; anything outside that range always reads 0.

Two gotchas. Losing the window focus (alt-tab, clicking another app) clears every held key, so a key you were holding reads 0 when you come back until you press it again. And FlushKeys does not affect KeyDown - it empties the hit counters and the typed-character queue, but a key that is physically still down carries on reading 1.

See also: KeyHit, GetKey, WaitKey, FlushKeys, ScanCodes, MouseDown.

Example

; KeyDown Example
; ---------------

Graphics 640,480,0,2
SetBuffer BackBuffer()

; Load the player ship sprite
ship=LoadImage("media/player.bmp")

x=320
y=400

While Not KeyDown(1)

    Cls

    ; KeyDown returns 1 for as long as a key is HELD, so the ship
    ; glides smoothly while an arrow key stays pressed.
    ; (Compare KeyHit, which reports each press only once.)
    If KeyDown(203) Then x=x-4 ; 203 = Left arrow
    If KeyDown(205) Then x=x+4 ; 205 = Right arrow
    If KeyDown(200) Then y=y-4 ; 200 = Up arrow
    If KeyDown(208) Then y=y+4 ; 208 = Down arrow

    ; Keep the ship inside the window
    If x<16 Then x=16
    If x>623 Then x=623
    If y<18 Then y=18
    If y>461 Then y=461

    DrawImage ship,x-16,y-18

    Text 0,0,"Hold the arrow keys to glide the ship   Esc: exit"
    Text 0,20,"KeyDown(203)="+KeyDown(203)+"  KeyDown(205)="+KeyDown(205)+"  KeyDown(200)="+KeyDown(200)+"  KeyDown(208)="+KeyDown(208)
    Text 0,40,"See the ScanCodes help page for the full key code list"

    Flip

Wend

End

Index