Subscribe to Dogstopper's Code Mania        RSS Feed
***** 1 Votes

An Input Manager Class

Icon 11 Comments
Input in Games is handled through a series of events that trigger either mouse, keyboard, etc. input. Often, trying to have multiple states of the game as well as hundreds of sprites all trying to grab input at the same time through meager event handling can be difficult. And how about when more than one key is held down? And how can you make this all take very little time later on? Well, let me introduce you to the InputManager class:

public class InputManager implements KeyListener {
	
	public static boolean leftPressed = false;
	public static boolean rightPressed = false;
	public static boolean upPressed = false;
	public static boolean downPressed = false;
	public static boolean spacePressed = false;

	@Override
	public void keyPressed(KeyEvent e) {
            // Edited this part due to pbl.
            int key = e.getKeyCode();
		if (key == KeyEvent.VK_LEFT)
			leftPressed = true;
		if (key == KeyEvent.VK_RIGHT)
			rightPressed = true;
		if (key == KeyEvent.VK_UP)
			upPressed = true;
		if (key == KeyEvent.VK_DOWN)
			downPressed = true;
		if (key == KeyEvent.VK_SPACE)
			spacePressed = true;
		if (key == KeyEvent.VK_ESCAPE)
			quit.cleanAndQuit();
	}

	@Override
	public void keyReleased(KeyEvent e) {
            // Edited this part due to pbl.
            int key = e.getKeyCode();
		if (key == KeyEvent.VK_LEFT)
			leftPressed = false;
		if (key == KeyEvent.VK_RIGHT)
			rightPressed = false;
		if (key == KeyEvent.VK_UP)
			upPressed = false;
		if (key == KeyEvent.VK_DOWN)
			downPressed = false;
		if (key == KeyEvent.VK_SPACE)
			spacePressed = false;
	}

	@Override
	public void keyTyped(KeyEvent e) {}
}



It's a really simple class that if a key is pressed, it sets a boolean to true, and when released, sets it to false. Additionally, if multiple keys are pressed an/or released, it works well because the program is not caught up in the event handling code. It merely sets a variable and moves on.

Now, in order to activate key handling to this class, set it like this in a constructor of the top-level class (a JPanel or JFrame).
addKeyListener(new InputManager());



Now, all you must do is to write a handleInput() method that updates a sprite's location if a key is pressed.

    public void doInput() {
		
        if (InputManager.rightPressed)
		xSpeed = 5;
	else if (InputManager.leftPressed))
		xSpeed = -5;
	else
		xSpeed = 0;
		
	if (InputManager.upPressed)
		ySpeed = -5;
	else if (InputManager.downPressed)
		ySpeed = 5;
	else 
		ySpeed = 0;
		
	if (InputManager.spacePressed) {
		// Jump...or shoot...or...something.
	}
			
    }



See how simple this is not to implement in real gaming situations? This class could also have private variables and methods if you don't believe in having this much access directly to variables. Additionally, if needed, this class could prove to be a fun Singleton project, but only if you have a need for one.

11 Comments On This Entry

Page 1 of 1

Java Student 

27 February 2010 - 05:37 PM
Nice tutorial :bigsmile: breif but to the point. Essential element for game development
0

Locke 

28 February 2010 - 02:32 PM
I think I'll make a nice edit to this class where you can input a number of elements in an array and use them all as keys to handle input.

But a very nice idea. :^:
0

toshiro 

28 February 2010 - 10:18 PM
this makes sense. I ended up using binary, but its all the same at the lower levels. Could there be some lag when lets say an array of sprites are accessing a single instance of the handler class? ie sprite at index 0 has an advantage over sprite at cell 99 in terms of collision detection between it and the ghosts.
0

Dogstopper 

01 March 2010 - 01:58 PM
Nice idea Locke by having the array! Like you said, this class pretty much serves as an *idea*. toshiro, If all of your sprites are on the same Timer and you have a simpe

handleInput()
update()
render()

style structure, them all of your sprites will respond to input, THEN all will update (check for collision, actually move), and then ALL will paint themselves. However, I am not entirely sure, and I have never encountered the issue.
0

pbl 

06 March 2010 - 07:35 PM
Very cute
love the design but not very efficient... you are calling e.getKeyCode() too many times for nothing when only one call will be sufficient.
If you want to add cases you will have to add them in 2 methods
This will be shorter and more efficient
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class InputManager implements KeyListener { 
         
        public static boolean leftPressed = false; 
        public static boolean rightPressed = false; 
        public static boolean upPressed = false; 
        public static boolean downPressed = false; 
        public static boolean spacePressed = false; 
 
        @Override 
        public void keyPressed(KeyEvent e) { 
        	int keyCode = e.getKeyCode();
            if (e.getKeyCode() == KeyEvent.VK_ESCAPE) 
                quit.cleanAndQuit(); 
            else
            	setState(keyCode, true);
        } 
 
        @Override 
        public void keyReleased(KeyEvent e) { 
        	int keyCode = e.getKeyCode();
        	setState(keyCode, false);
        } 
 
        @Override 
        public void keyTyped(KeyEvent e) {}

        void setState(int keyCode, boolean state) {
        	switch(keyCode) {
	        	case KeyEvent.VK_LEFT:
	        		leftPressed = state;
	        		break;
	        	case KeyEvent.VK_RIGHT:
	        		rightPressed = state;
	        		break;
	        	case KeyEvent.VK_UP:
	        		upPressed =  state;
	        		break;
	        	case KeyEvent.VK_DOWN:
	        		downPressed = state;
	        		break;
	        	case KeyEvent.VK_SPACE:
	        		spacePressed = state;
	        		break;
        	}
        }
}


But I really like the idea of an InputManager
Good show :^:
2

Dogstopper 

06 March 2010 - 10:06 PM
Great idea pbl, great modification! I will change this up a little bit!

I also like the idea of a helper method. I'm not going to change that part because I didn't think of that, though it does save code. Will definately think about ideas such as that next time.
0

japanir 

14 March 2010 - 10:07 AM
That's Excellent Dogstopper! very helpful and descriptive! I am now started writing games and i find your blog very helpful!
Great job :)
0

Dogstopper 

14 March 2010 - 07:13 PM
Well thanks japanir! I am very glad that you find my blog useful! That's the reason I have it and now I know my efforts have paid off.
0

NeoTifa 

12 August 2010 - 11:54 AM
:D Muy bueno! <3
0

Krbshadow 

22 May 2012 - 02:03 PM
my text line won't work for some reason.

if (key == keyEvent.VK_[i]ESCAPE[/i])
quit.cleanAndQuit();



quit has been underlined in red and it says that it cannot be resolved. any ideas on how to fix this?
0

Krbshadow 

22 May 2012 - 02:08 PM
my text line won't work for some reason.

if (key == keyEvent.VK_ESCAPE)
quit.cleanAndQuit();



quit has been underlined in red and it says that it cannot be resolved. any ideas on how to fix this?
0
Page 1 of 1

December 2020

S M T W T F S
  1 2 345
6789101112
13141516171819
20212223242526
2728293031  

Recent Entries

Search My Blog

Recent Comments

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)