Full Version: Video Game Applet pt 2
Dream.In.Code > Programming Tutorials > Java Tutorials
WolfCoder
I was going to tech about MouseListeners for games but Asyncronized keyboard input is better for action games.

This is a rather short tutorial but it's valuable. Consider the following class definition:
CODE

import java.awt.event.*;
public class GameKey implements KeyListener // Keyboard input
{
    public boolean key_right,key_left,key_up,key_down,key_z,key_x;
    public void keyTyped(KeyEvent e){}
    public void keyPressed(KeyEvent e)
    {
 if(e.getKeyCode() == e.VK_DOWN)
     key_down = true;
 if(e.getKeyCode() == e.VK_UP)
     key_up = true;
 if(e.getKeyCode() == e.VK_LEFT)
     key_left = true;
 if(e.getKeyCode() == e.VK_RIGHT)
     key_right = true;
 if(e.getKeyCode() == e.VK_Z)
     key_z = true;
 if(e.getKeyCode() == e.VK_X)
     key_x = true;
    }
    public void keyReleased(KeyEvent e)
    {
 if(e.getKeyCode() == e.VK_DOWN)
     key_down = false;
 if(e.getKeyCode() == e.VK_UP)
     key_up = false;
 if(e.getKeyCode() == e.VK_LEFT)
     key_left = false;
 if(e.getKeyCode() == e.VK_RIGHT)
     key_right = false;
 if(e.getKeyCode() == e.VK_Z)
     key_z = false;
 if(e.getKeyCode() == e.VK_X)
     key_x = false;
    }
}


It is a simple class that implements a KeyListener interface. It contains some booleans on the current state of the key. All of that key repeat rate stuff is bad for video games. Since the events are fired to key repeat rate specifications (There is a short pause until the event is fired continuously), this type of code is needed.

The boolean is set to true when THE VERY FIRST TIME the keyPressed event is fired.

To maintain the asyncronized input, the boolean is set to false immeadiatly when the key is released.

Now, here is a code cutout of how you would implement this into a panel or what have you:

CODE

setFocusable(true); // Required for keyboard input
GameKey game_key = new GameKey(); // Variable needed to get key states
addKeyListener(game_key); // Add it to your game


And when you want to read from the current state of the keyboard input, you simply do this:

CODE

if(game_key.key_z)
{
  // Key was pressed
}


If you want your own keys defined, add the corresponding code to keyPressed and keyReleased.

There you have it.
Fame Commeth
Wow! That solves so many problems! Thanks!

hehe:

postcount++;
jhoy
QUOTE(Fame Commeth @ 5 Mar, 2006 - 01:18 PM) *

Wow! That solves so many problems! Thanks!

hehe:

postcount++;

This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.