Author Topic: Joystick filtering  (Read 1715 times)

MrTAToad

  • Guest
Joystick filtering
« on: 2009-Mar-14 »
Because joysticks are weird things, especially when not calibrated, I have devised this routine to not only filter joystick movement (based on the Joypad2 example code) but also prevent multiple readings where such would cause problems if the user kept holding down a button or HAT position.

Code: (glbasic) [Select]
// --------------------------------- //
// Project: Press Press Evolution
// Start: Saturday, March 14, 2009
// IDE Version: 6.192

TYPE tJoypad
x
y
z
button%
hasMoved%
hasPressed%
ENDTYPE

GLOBAL MAX_JOYPADS% = 10
GLOBAL MAX_JOYBUTTONS% = 32

GLOBAL JOYPAD_FILTER_XYZ% = 1
GLOBAL JOYPAD_FILTER_BUTTONS% = 2

GLOBAL joypadFilter[] AS tJoypad

FUNCTION initialiseJoyPadFilter%:
LOCAL loop1%
LOCAL joy AS tJoypad

DIM joypadFilter[0]

FOR loop1%=0 TO MAX_JOYPADS%-1
joy.x=0.0
joy.y=0.0
joy.z=0.0
joy.button%=0
joy.hasMoved%=FALSE
joy.hasPressed%=FALSE

DIMPUSH joypadFilter[],joy
NEXT

RETURN GETNUMJOYSTICKS()
ENDFUNCTION

FUNCTION readJoypadFilter%:joyIndex%,BYREF joyX,BYREF joyY,BYREF joyZ,BYREF button%,flags%
LOCAL loop%
LOCAL temp$
LOCAL x,y,z
LOCAL value%

IF joyIndex%>=BOUNDS(joypadFilter[],0)
RETURN FALSE
ENDIF

temp$=FORMAT$(4,1,GETJOYX(joyIndex%)); x=temp$
temp$=FORMAT$(4,1,GETJOYY(joyIndex%)); y=temp$
temp$=FORMAT$(4,1,GETJOYZ(joyIndex%)); z=temp$

IF bAND(flags%,JOYPAD_FILTER_XYZ%)
IF x<>0.0 OR y<>0.0 OR z<>0.0
IF joypadFilter[joyIndex%].hasMoved%=FALSE
joypadFilter[joyIndex%].x=x
joypadFilter[joyIndex%].y=y
joypadFilter[joyIndex%].z=z
joypadFilter[joyIndex%].hasMoved%=TRUE
ENDIF

x=0.0
y=0.0
z=0.0
ELSE
IF joypadFilter[joyIndex%].hasMoved%=TRUE
x=joypadFilter[joyIndex%].x
y=joypadFilter[joyIndex%].y
z=joypadFilter[joyIndex%].z
ELSE
x=0.0
y=0.0
z=0.0
ENDIF
ENDIF
ENDIF

joyX=x
joyY=0.0-y
joyZ=z

value%=0
FOR loop%=0 TO MAX_JOYBUTTONS%-1
IF GETJOYBUTTON(joyIndex%,loop%)
INC value%,POW(2,loop%)
ENDIF
NEXT

IF bAND(flags%,JOYPAD_FILTER_BUTTONS%)
IF value%<>0
IF joypadFilter[joyIndex%].hasPressed%=FALSE
joypadFilter[joyIndex%].button%=value%
joypadFilter[joyIndex%].hasPressed%=TRUE
ENDIF

button%=0
ELSE
IF joypadFilter[joyIndex%].hasPressed%=TRUE
button%=joypadFilter[joyIndex%].button%
joypadFilter[joyIndex%].hasPressed%=FALSE
ELSE
button%=0
ENDIF
ENDIF
ENDIF

RETURN TRUE
ENDFUNCTION