Skip to main content
gamedev.net
🔒 Locked

Java: Smooth Keyboard Input?

Started by SpaceRook Sep 30, 2005 at 6:57 PM 4 replies 15k views
Original Post
SpaceRook
SpaceRook
Hello, I've returned to game programming after a long absence, and have decided to use Java to make some simple games. My main problem right now is with keyboard input. It seems like using the tradional event based model leads to cumbersome controls. For example, if you press and hold the left arrow key, my guy will move one step, pause for a second, and then start to move again. How can I achieve smooth, realtime keyboard input? I want input that is as sensitive as a gamepad and shooters like Quake. I know it is possible, but I have not found information beyond the basic input tutorials like this: http://www.gamedev.net/reference/articles/article1360.asp
Kevinator
Kevinator
Do something like this:

public class Player implements KeyListener {    public static final int SPEED = 3;    private int vX, // velocity x                vY, // vel y                x,  // pos x                y;  // pos y    private boolean up,                    down,                    left,                    right;/* This is the only method that the client should ever call!   Instead of moving a sprite when you press a button,   you should be moving a sprite while certain states   hold. Also, do not animate the sprite in the event   handler! Animate it in your main rendering loop!!   That means that your main rendering loop will call   player.go() and nothing more. This will result in   smooth animation. If you rely on animating the sprite   in the keypressed method, the sprite will only move   when an event is fired. That's ugly!! */public void go() {    x += vX;    y += vY;    // etc...}private void update() {    vX = 0;    vY = 0;    if(down) vY = SPEED;    if(up) vY = -SPEED;    if(left) vX = -SPEED;    if(right) vX = SPEED;}public void keyPressed(KeyEvent e) {    switch(e.getKeyCode()) {        case KeyEvent.VK_DOWN: down = true; break;        case KeyEvent.VK_UP: up = true; break;        case KeyEvent.VK_LEFT: left = true; break;        case KeyEvent.VK_RIGHT: right = true; break;    }    update();}    public void keyReleased(KeyEvent e) {	switch(e.getKeyCode()) {	    case KeyEvent.VK_DOWN: down = false; break;	    case KeyEvent.VK_UP: up = false; break;	    case KeyEvent.VK_LEFT: left = false; break;	    case KeyEvent.VK_RIGHT: right = false; break;	}	update();    }}
SpaceRook
SpaceRook
Thanks. I tried this strategy and it worked quite well. I can definitely get Super-Mario quality controls with this (which is what I'm after). I have a little circle that can walk, run, and jump. Now it's just a matter of tweaking the controls.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.