Joysticks and Gamepads

Top  Previous  Next

Using a joystick or gamepad device in your program requires an open screen or manual initialization of DirectInput. The 2D command set supports any number of connected joystick devices and supports a maximum of 32 buttons per device and a maximum of 3 axes per device (X, Y and Z).

 

Getting the number of devices and their names.

To determine the number of joystick devices attached to the system use the GETJOYSTICKCOUNT function. Once the number of devices is obtained use a loop to retrieve the names of the devices to present to the user if desired with the GETJOYSTICKNAME function.
 

joycount = GETJOYSTICKCOUNT
FOR x = 0 TO joycount-1
    name$ = GETJOYSTICKNAME( x )
    ' do something with the name
NEXT x

The name returned is usually descriptive such as "2 button, 2 axis joystick" and may include the manufacturers name.

Device types

A joystick devices type can be obtained using the GETJOYSTICKTYPE function. The returned value will be one of the following constants:

@JOYTYPE_UNKNOWN

@JOYTYPE_TRADITIONAL

@JOYTYPE_FLIGHTSTICK

@JOYTYPE_GAMEPAD

@JOYTYPE_RUDDER

@JOYTYPE_WHEEL

@JOYTYPE_HEADTRACKER

Use the type to determine if the device is usable in your program

 

Device settings

Once a device is chosen by the user, or by your program, set up the axis ranges and dead-zones as required for your application. The number of axes supported by the device can be retrieved with the GETJOYSTICKAXISCOUNT function. Use GETJOYSTICKBUTTONCOUNT to retrieve the number of buttons the device has.

The range of a joystick axis is set by the SETJOYSTICKRANGE function. The default range is from -1000 to +1000 and will be the range of values returned when querying the device.

The dead-zone of an axis is set by the SETJOYSTICKDEADZONE function. A dead-zone is a percentage of the range of movement about the center of the axis where the joystick will report being at the center of its range. The default dead-zone is 10%.

Example of setting up the device:

SETJOYSTICKRANGE @XAXIS, -32767, 32767, 1
SETJOYSTICKRANGE @YAXIS, -32767, 32767, 1
SETJOYSTICKDEADZONE @XAXIS, 8.5, 1
SETJOYSTICKDEADZONE @YAXIS, 8.5, 1

A digital joystick will report the minimum and maximum for a particular axis.

Reading the device

The current positions of the axes can be retrieved at any time using the JOYX, JOYY, and JOYZ functions. While an axis is in its dead-zone the functions will return 0.  For example to read the three axes of the second joystick:
 

posy = JOYY(1)
posx = JOYX(1)
posz = JOYZ(1)

Use JOYDOWN to determine if a particular button on the device is currently being pressed. JOYDOWN returns 1 if the button is down or 0 if  up. Button numbers are zero based so to check the 4th button on device number 1:
 

IF JOYDOWN( 3, 1) = 1 THEN fire_missle = TRUE