Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joystick + c# : Analog button

I am using Microsoft DirectX to get access to my gamepad. This is an usb gamepad like this one:

enter image description here

I could get access to know when buttons are pressed and also the analog values of the axis...

The thing is if there is a way to know when the analog button is pressed (Red light on).

Is that possible? How?

like image 423
the_moon Avatar asked Mar 12 '26 18:03

the_moon


1 Answers

I would recommend SlimDX or SharpDX for your Project. They support the DirectX API and are really simple.

SlimDX:

using SlimDX.DirectInput;

Create a new DirectInput-Object:

DirectInput input = new DirectInput();

Then a GameController Class for Handling:

public class GameController
{
    private Joystick joystick;
    private JoystickState state = new JoystickState();
}

And use it like this:

public GameController(DirectInput directInput, Game game, int number)
{
    // Search for Device
    var devices = directInput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly);
    if (devices.Count == 0 || devices[number] == null)
    {
        // No Device
        return;
    }

    // Create Gamepad
    joystick = new Joystick(directInput, devices[number].InstanceGuid);  
    joystick.SetCooperativeLevel(game.Window.Handle, CooperativeLevel.Exclusive | CooperativeLevel.Foreground);

    // Set Axis Range for the Analog Sticks between -1000 and 1000 
    foreach (DeviceObjectInstance deviceObject in joystick.GetObjects())
    {
        if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0)
            joystick.GetObjectPropertiesById((int)deviceObject.ObjectType).SetRange(-1000, 1000);
    }
    joystick.Acquire();
}

Finally get per Method the State:

public JoystickState GetState()
{
    if (joystick.Acquire().IsFailure || joystick.Poll().IsFailure)
    {
        state = new JoystickState();
        return state;
    }

    state = joystick.GetCurrentState();

    return state;
}
like image 191
Smartis Avatar answered Mar 15 '26 08:03

Smartis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!