The code is just me building up on InputExample from the LWJGL Basics 2 (Input) tutorial.
I’m trying to figure out how to get controllers to work and so far all I’ve figured out is how to find out:
- what controllers are connected
- what buttons and axis are available
- if a button is pressed
But I can’t for the life of me figure out how to find out what button is pressed. Can anyone help me out with that? Here’s the code. Sorry if there are some clumsily made stuff in there, I’m just learning the ropes.
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Controller;
import org.lwjgl.input.Controllers;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
public class InputExample {
Controller[] c;
int gp=-1; //to store controller number of the gamepad
public void start() {
try {
Display.setDisplayMode(new DisplayMode(800,600));
Display.setLocation(43, 12);
Display.create();
int cc=0;
try{
Controllers.create();
cc = Controllers.getControllerCount();
} catch (LWJGLException e) {
e.printStackTrace();
System.exit(0);
}
c = new Controller[cc];
for(int i=0; i<cc;i++){
c[i] = Controllers.getController(i);
if(c[i].getName().indexOf("Controller") > -1){
gp=i;
}
}
if(gp==-1){
System.out.println("No gamepad controller exists.");
}else{
int bc = c[gp].getButtonCount();
int ac = c[gp].getAxisCount();
System.out.println("The controller has "+bc+" buttons and "+ac+" axis.");
for(int i=0; i<bc;i++){
System.out.println(c[gp].getButtonName(i));
}
}
} catch (LWJGLException e) {
e.printStackTrace();
System.exit(0);
}
// init OpenGL here
while (!Display.isCloseRequested()) {
// render OpenGL here
pollInput();
Display.update();
}
Display.destroy();
}
public void pollInput() {
if(gp>-1){
if(c[gp].isButtonPressed(gp)){
System.out.println(c[gp].getButtonName(gp)+" is pressed.");
}
}
while(Controllers.next()){
System.out.println("Event came from "+Controllers.getEventSource().getName()+".");
}
if (Mouse.isButtonDown(0)) {
int x = Mouse.getX();
int y = Mouse.getY();
System.out.println("MOUSE DOWN @ X: " + x + " Y: " + y);
}
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
System.out.println("SPACE KEY IS DOWN");
}
while (Keyboard.next()) {
if (Keyboard.getEventKeyState()) {
if (Keyboard.getEventKey() == Keyboard.KEY_A) {
System.out.println("A Key Pressed");
}
if (Keyboard.getEventKey() == Keyboard.KEY_S) {
System.out.println("S Key Pressed");
}
if (Keyboard.getEventKey() == Keyboard.KEY_D) {
System.out.println("D Key Pressed");
}
} else {
if (Keyboard.getEventKey() == Keyboard.KEY_A) {
System.out.println("A Key Released");
}
if (Keyboard.getEventKey() == Keyboard.KEY_S) {
System.out.println("S Key Released");
}
if (Keyboard.getEventKey() == Keyboard.KEY_D) {
System.out.println("D Key Released");
}
}
}
}
public static void main(String[] argv) {
InputExample inputExample = new InputExample();
inputExample.start();
}
}