Plugging in controllers at runtime?

Started by w1th0utnam3, January 14, 2012, 10:35:49

Previous topic - Next topic

w1th0utnam3

My project should be controllable with the Xbox Controller which is of course no problem. But I want to add the possibility to use a controller which was connected at runtime but the return of getControllerCount() does not change after the application starts no matter which device I plug in or out. Do I have to use another method for this?

BTW: Here is the method that makes use of this, if you have any other advice concerning this piece of code please comment.
public void refresh() {    
  // Get the number of connected controller devices
  int count = Controllers.getControllerCount();
  System.out.println(count);
  // If something changed check whether there is a new Xbox Controller or one disappeared
  if (count != deviceCount) {
    // Save the number of connected controller devices
    this.deviceCount = Controllers.getControllerCount();
    // Loop through all devices and search for a Xbox Controller
    for (int i = 0; i < this.deviceCount; i++) {
      Controller possibleController = Controllers.getController(i);
      if (possibleController.getName().contains("XBOX 360 For Windows (Controller)")) {
        // Only update the controller reference if it changed
        if (!possibleController.equals(this.controller)) {
          // Save the controller device
          this.controller = possibleController;
          System.out.println("New Xbox controller found as device " + this.controller.getIndex());
          // Exit the method if a Xbox Controller was found
          return;
        }
        // Just exit the method if the old Xbox Controller is still available
        else {
          return;
        }
      }
    }
    // If no Xbox Controller was found delete reference to the old one
    this.controller = null;
    System.out.println("Xbox controller was unplugged");
  }
} // refresh();

Fool Running

A couple things:
1) It's common behavior for games to need a restart when adding game controllers so I wouldn't worry about it too much.
2) Limiting the controller to an Xbox controller seems a little bit restrictive (Personally I hate games that require an Xbox controller because I don't have one). And limiting it to a device that has the string "XBOX 360 For Windows (Controller)" seems even worse.
Programmers will, one day, rule the world... and the world won't notice until its too late.Just testing the marquee option ;D

Endolf

JInput doesn't support hot plugging currently, it's been asked for a few times, but nobody seems to want it badly enough to contribute the code, so it's not been done.

Endolf