I am building a robot simulator to simulate how the robot will move and react to friction and other outside events. I have it working using the arrow keys for input, but I am trying to get it working with a joystick. I am using slick2D per recommendation. I have never used slick2D and am very confused about how to make my program work. What classes in slick should I use?
According to Slick2D's forums, JInput is the preferred method for working with a Joystick.
According to java-gaming.org, JInput requires native libraries to work (.dll, .so or .dylib, depending on your platform).
Here's the example copied from java-gaming:
/* Gets a list of the controllers JInput knows about and can interact with */
Controller[] ca = ControllerEnvironment.getDefaultEnvironment().getControllers();
for(int i =0;i<ca.length;i++){
/* Get the name of the controller */
System.out.println(ca[i].getName());
/* Gets the type of the controller, e.g. GAMEPAD, MOUSE, KEYBOARD */
System.out.println("Type: "+ca[i].getType().toString());
/* Get this controllers components (buttons and axis) */
Component[] components = ca[i].getComponents();
System.out.println("Component Count: "+components.length);
for(int j=0;j<components.length;j++){
/* Get the components name */
System.out.println("Component "+j+": "+components[j].getName());
/* Gets its identifier, E.g. BUTTON.PINKIE, AXIS.POV and KEY.Z */
System.out.println(" Identifier: "+ components[j].getIdentifier().getName());
/* Display if component is relative, absolute, analog, digital */
System.out.print(" ComponentType: ");
if (components[j].isRelative()) {
System.out.print("Relative");
} else {
System.out.print("Absolute");
}
if (components[j].isAnalog()) {
System.out.print(" Analog");
} else {
System.out.print(" Digital");
}
}
}
Getting values requires polling the device or using Event Queues.
Warning, this next block is written in an infinite loop, which can block other code from executing, a good candidate for a dedicated thread.
while(true) {
Controller[] controllers = ControllerEnvironment.getDefaultEnvironment().getControllers();
if(controllers.length==0) {
System.out.println("Found no controllers.");
break;
}
for(int i=0;i<controllers.length;i++) {
controllers[i].poll();
EventQueue queue = controllers[i].getEventQueue();
Event event = new Event();
while(queue.getNextEvent(event)) {
StringBuffer buffer = new StringBuffer(controllers[i].getName());
buffer.append(" at ");
buffer.append(event.getNanos()).append(", ");
Component comp = event.getComponent();
buffer.append(comp.getName()).append(" changed to ");
float value = event.getValue();
if(comp.isAnalog()) {
buffer.append(value);
} else {
if(value==1.0f) {
buffer.append("On");
} else {
buffer.append("Off");
}
}
System.out.println(buffer.toString());
}
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}