如何检测用户何时真正在 Java 中释放了一个键?
How can I detect when a user really released a key in Java?
如果你按下一个键,玩家就会前进,但如果你按住键的时间稍长,玩家就会向同一个方向移动太久。
我正在使用此代码来检查播放器按下的键:
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();
}
}
使用 keyReleased !!!如果您需要在每次按键时将播放器移动一步
当用户按下键
时,keyPressed 保持 运行
使用 THREADS 是因为您在这里使用的是该程序,但是如果您启动一个线程,您可以做任何您想做的事情,该程序仍然可以正常工作
了解线程,因为游戏都是关于线程的
private class Walk_thread extends java.lang.Thread{
public void run(){
//call the walk methode here
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");
}
如果你按下一个键,玩家就会前进,但如果你按住键的时间稍长,玩家就会向同一个方向移动太久。 我正在使用此代码来检查播放器按下的键:
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();
}
}
使用 keyReleased !!!如果您需要在每次按键时将播放器移动一步 当用户按下键
时,keyPressed 保持 运行使用 THREADS 是因为您在这里使用的是该程序,但是如果您启动一个线程,您可以做任何您想做的事情,该程序仍然可以正常工作 了解线程,因为游戏都是关于线程的
private class Walk_thread extends java.lang.Thread{
public void run(){
//call the walk methode here
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");
}