简体   繁体   English

如何检测用户何时真正释放了 Java 中的密钥?

[英]How can I detect when a user really released a key in Java?

If you press a key, the player goes forward, but if you hold the key a bit longer the player moves too long in the same direction.如果你按下一个键,玩家会向前移动,但如果你按住键的时间更长一点,玩家会向同一方向移动太久。 I am using this code to check what key the player is pressing:我正在使用此代码来检查播放器按下的键:

private void KeyPressed(java.awt.event.KeyEvent evt) {

    key = evt.getKeyCode();

        if (key == KeyEvent.VK_W) {

            direction = 1;

            PlayerMovement();
        }
        if (key == KeyEvent.VK_S) {

            direction = 2;

            PlayerMovement();
        }
        if (key == KeyEvent.VK_D) {

            direction = 3;

            PlayerMovement();
        }
        if (key == KeyEvent.VK_A) {
            direction = 4;
            PlayerMovement();

        }
}

use keyReleased !!!使用 keyReleased !!! if you need to move the player one step in evry key press keyPressed keeps running when the user is pressing the key如果您需要在每个按键中将播放器移动一步,请按下 keyPressed 在用户按下该键时保持运行

use THREADS because here you are using the program but if you start a thread you can do what ever you want the program still works fine learn about thread because game are all about threads使用线程,因为在这里您正在使用该程序,但是如果您启动一个线程,您可以做任何您想做的事情该程序仍然可以正常工作学习线程,因为游戏都是关于线程的

private class Walk_thread extends java.lang.Thread{

public void run(){
//call the walk methode here
PlayerMovement();
}
}

so when the key is pressed create a thread that call playermovement所以当按键被按下时创建一个调用 playermovement 的线程

if (key == KeyEvent.VK_W) {

        direction = 1;
new Walk_thread().start();//here the method run is called 
System.out.println("program will not stop the thread is walking and the program is continued too");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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