Game Development Reference
In-Depth Information
Using joysticks with DirectInput
Now, let's shift gears and take a look at using
joysticks
. In this topic, we will use the
term joystick to refer to any game controller. First, we will look at how to use joysticks
with DirectInput.
Enumerating devices
You've probably seen some games that let you choose which game controller you
want to use if you have more than one attached to your PC. In this section, we are go-
ing to look at how to get the list of available devices. With SlimDX, it is actually quite
easy.
The
DirectInput
object (remember that we stored it in our
m_DirectInput
mem-
ber variable) has a method named
GetDevices()
. To get a list of the available con-
trollers, we would call that method like this:
m_DirectInput.GetDevices(DeviceClass.GameController,
DeviceEnumerationFlags.AttachedOnly);
To try this out, let's add a new method to our
UserInput.cs
class. This method will
simply write some debug output about the available devices. Here is the code:
public void GetJoysticks()
{
IList<DeviceInstance> deviceList =
m_DirectInput.GetDevices(DeviceClass.GameController,
DeviceEnumerationFlags.AttachedOnly);
if (deviceList.Count < 1)
{
System.Diagnostics.Debug.WriteLine("NO GAME
CONTROLLERS WERE FOUND!");
}
else
{
foreach (DeviceInstance device in deviceList)