Archived

This topic is now archived and is closed to further replies.

stickman

[java] keyboard input

Recommended Posts

hello im trying to make a 2d spaceship game in java. its gunna be an applet. when i did a program in C++ i remeber being able to just test if a button was DOWN or not. but i dunno how to do this in java. my problem is my ship cannot turn and move forward at the same time. my program only sends down 1 keypressed event at a time.
addKeyListener(new KeyAdapter()
            { 
                public void keyPressed(KeyEvent e)
                {   
                    if(e.getKeyCode() == KeyEvent.VK_RIGHT)   
                    {      
                        frame = (frame+1)%images.length;
                    }                    
                    if(e.getKeyCode() == KeyEvent.VK_LEFT)   
                    {      
                        frame = (frame+images.length-1)%images.length;
                    }
                    if(e.getKeyCode() == KeyEvent.VK_UP)
                    {
                        ship1x = ship1x + ship1_speed*Math.cos((90+(30-frame)*12)*(Math.PI/180));
                        ship1y = ship1y - ship1_speed*Math.sin((90+(30-frame)*12)*(Math.PI/180));
                    }
                }  
                public void keyReleased(KeyEvent e)
                {   

                } 
            });
can anyone tell me how i can find out what buttons the user is pushing if he is pushing multiple buttons [edited by - stickman on July 26, 2003 4:08:58 PM] [edited by - stickman on July 26, 2003 4:10:04 PM]

Share this post


Link to post
Share on other sites
Every KeyEvent only corresponds to one key press. So if your user presses two buttons, that will generate two events, one immediately after the other. Your keylistener is invoked in another thread automatically. So let it sit off on its own and just keep track of what's pressed and whats not. Then use that info in the main part of your game.

Instead of doing your logic right in the key listener, just use it to set flags.


boolean leftDown, upDown;

public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_LEFT )
leftDown = true;

if(e.getKeyCode() == KeyEvent.VK_UP )
upDown = true;
}

public void keyReleased(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_LEFT )
leftDown = false;

if(e.getKeyCode() == KeyEvent.VK_UP )
upDown = false;
}

...

void playGame()
{
while(true)
{
...
if(leftDown && upDown)
// player wants to go diagonally left

...
}
}


but be warned. This will not work in Linux and possibly other Unix like OSes. But trying to get keyboard input for a game with AWT in Linux is practically futile anyway, so you mine as well not worry about it.

Eventually Java games won't use AWT, but JInput or something similiar to it. Which will allow direct polling of keys.

[edited by - tortoise on July 26, 2003 4:59:59 PM]

Share this post


Link to post
Share on other sites