0 Replies - 10274 Views - Last Post: 11 February 2015 - 03:05 PM

#1 mike73   User is offline

  • D.I.C Addict
  • member icon

Reputation: 250
  • View blog
  • Posts: 918
  • Joined: 24-April 10

Basic InputHandler for Java Games

Post icon  Posted 11 February 2015 - 03:05 PM

Over time I've pieced together a simple input handler for beginners making games.

import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class InputHandler implements KeyListener {
	
	// Depending on keys allowed, you can change this range
	private static final int NUM_KEYS = 256;
	
	// Stores keys which are currently being held down
	private static final boolean[] KEY_STATES = new boolean[NUM_KEYS];
	
	// Counts how long a key was held down.
	private static final int[] KEYS_POLLED = new int[NUM_KEYS];
	
	// The single instance of our class.
	private static InputHandler instance = new InputHandler();;
	
	// Private constructor, using a singleton model.
	private InputHandler() {
	}
	
	// Return an instance of our class.
	public static InputHandler getInstance() {
		return instance;
	}
	
	// If a key was held down, increase its poll count. Called once on each game loop iteration.
	public void pollKeys() {
		for(int i = 0; i < NUM_KEYS; i++) {
			if(KEY_STATES[i]) {
				KEYS_POLLED[i]++;
			}
			else {
				KEYS_POLLED[i] = 0;
			}
		}
	}
	
	// Check if a particular key is held down.
	// e.g: if(....isDown(KeyEvent.VK_W)) { do something }
	public boolean keyDown(int code) {
		if(code >= 0 && code < NUM_KEYS) {
			return KEY_STATES[code];
		}
		return false;
	}
	
	// You may want a particular key to only be acted upon once, no matter
	// how long you hold it down.
	// E.g: For a game menu, if the user holds down, you may only want to go to the 
	// next menu item, and not scroll all the way to the bottom.
	public boolean keyDownOnce(int code) {
		if(code >= 0 && code < NUM_KEYS) {
			return KEYS_POLLED[code] == 1;
		}
		return false;
	}
	
	// Add the new key value as pressed.
	@Override
	public void keyPressed(KeyEvent e) {
		int code = e.getKeyCode();
		if(code >= 0 && code < NUM_KEYS) {
			KEY_STATES[code] = true;
		}
	}
	
	// Add the new key value as released.
	@Override
	public void keyReleased(KeyEvent e) {
		int code = e.getKeyCode();
		if(code >= 0 && code < NUM_KEYS) {
			KEY_STATES[code] = false;
		}
	}
	
	// Don't really need this.
	@Override
	public void keyTyped(KeyEvent e) {
		// We don't care about this one.
	}
}


Sample usage:
private InputHandler input = InputHandler.getInstance();
public GameCanvas() {
	addKeyListener(input);
}

public void update(float dt) {
	input.pollKeys();
	if(input.keyDown(KeyEvent.VK_W)) {
		// move player up
	}
}


Have fun!

Is This A Good Question/Topic? 2
  • +

Page 1 of 1