简体   繁体   中英

How to make key board commands in java

I just started making an RPG with my friend. We want to be able to move the character around, using either arrow keys, or WASD. I don't know how to do so, and I've been looking over the internet for a bit. I know I have to use ActionListener, but beyond that, I have no idea what I'm doing with it. This is the part of the code that uses the keyboard input, but I don't know what to do to

public class Character implements ActionListener
 {
  public static char KBoard(char w, char a, char s, char d)
   {
     /_\-|(This is what I need help with, reading in the keyboard input)|-/_\
     return kBoard;
    }
   public static int MoveX (int velocity)
    {
     velocity = 5

     Switch (kBoard)

     case 'w':
     characterPosX -= velocity;
     break;

     case 's':
     characterPosX += velocity;
     break;

     return characterPosY;
    }
   public static int MoveY (int velocity)
    {
     velocity = 5

     Switch (kBoard)

     case 'a':  
     characterPosY -= velocity;
     break;

     case 'd':    
     characterPosY += velocity;
     break;
     return characterPosY;
    }
   public void Character ()
    {
      (code to make the character appear)
    }
   }

You don't need action listener. You need to use a scanner - one that reads in the input, constantly.

public static char KBoard(char w, char a, char s, char d)
{
    Scanner scan = new Scanner(System.in);
    System.out.print("");
    char kBoard = scan.nextChar();
    return kBoard;
}

But hey, now if anyone needs to know, they can look here. You can also add a filter here, an if-else statement, to make sure that the only chars getting passed in are the chars you want, and none of the others will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM