Input testing across platforms

Previous topic - Next topic

AndyH

Thought I'd post this in case it is of any use to someone.  A snippet of code from my game where I handle mouse, joystick and keyboard inputs.  Tested on PC and PocketPC so far, the plan would be to refine it more as I get to test it on Mac / Linux and GP2X devices.  For the PocketPC side, it omits the tests that really slows the PPC down (I was loosing up to 10 frames per second testing for joystick or keys that do not exist on the PPC).

Code (glbasic) Select
TYPE tInput
x;y // x and y values
fire // firebutton
lx;ly // last x and y pressed flags (for key+joy) 0 =not pressed, 1=just pressed, 2=held down state
lfire // fire last pressed flag
mx;my // mouse pos
ma;mb // mouse buttons
ENDTYPE

// all these globals are stored in a game type but I've extracted them to separate globals here for simplicity
GLOBAL inp as tInput
GLOBAL devices$
devices$ = PLATFORMINFO$("DEVICE")
GLOBAL numjoy
numjoy = GETNUMJOYSTICKS()



GetAllInputs( inp )

// now can test values in inp.x, inp.y for example,  inp.mx and inp.my for mouse
// lx, ly, lfire contain 1 if direction x / y / firebutton just pressed, or 2 if currently held


FUNCTION GetAllInputs: inp AS tInput
LOCAL vx, xx,yy, ff, i, kf

xx=0
yy=0
ff=0
kf=0
IF devices$<>"POCKETPC"
IF numjoy>0
xx=GETJOYX(0)
yy=GETJOYY(0)
FOR i=0 TO 3
IF GETJOYBUTTON(0,i) THEN ff=1
NEXT
ENDIF

IF KEY(29) OR KEY(57) THEN kf=1
ENDIF
IF KEY(28) THEN kf=1

// if XX val returned not moved, check for keys instead
IF xx>=-0.1 AND xx<=0.1
xx=0
IF KEY(203) THEN xx=-0.5
IF KEY(205) THEN xx=0.5
IF kf=1
xx=xx*2
ff=1
ENDIF
ENDIF
// if YY val returned not moved, check for keys instead
IF yy>=-0.1 AND yy<=0.1
yy=0
IF KEY(200) THEN yy=-0.5
IF KEY(208) THEN yy=0.5
IF kf=1
yy=yy*2
ff=1
ENDIF
ENDIF
inp.x=xx
inp.y=yy
inp.fire=ff
IF inp.x <> 0
IF inp.lx < 2 THEN INC inp.lx,1
ELSE
inp.lx=0
ENDIF
IF inp.y <> 0
IF inp.ly < 2 THEN INC inp.ly,1
ELSE
inp.ly=0
ENDIF
IF inp.fire <> 0
IF inp.lfire < 2 THEN INC inp.lfire,1
ELSE
inp.lfire=0
ENDIF
MOUSESTATE inp.mx, inp.my, inp.ma, inp.mb

ENDFUNCTION

bigsofty

As usual Andy very nice (and useful) coding! :)
Cheers,

Ian.

"It is practically impossible to teach good programming style to students that have had prior exposure to BASIC.  As potential programmers, they are mentally mutilated beyond hope of regeneration."
(E. W. Dijkstra)

AndyH

Forgot to mention - this code snippet is treating the first four fire buttons as a single fire button.  So Joypads on PC's and the A,B,X,Y buttons on the GP2X will be 'FIRE'.

I've now split fire into the four main buttons (plus two shoulder buttons) so I can test for them separately, but it is more or less the same code.