简体   繁体   English

如何在按住键的同时阻止对象移动

[英]How to stop object from moving while key is still pressed

I'm a beginner in Java programming & I am making an application requiring an object to move around a grid filled with squares. 我是Java编程的初学者,我正在制作一个应用程序,要求对象在充满正方形的网格周围移动。

The object should only move one square at a time and if the user wants to move into another square, they must press the key again. 对象一次只能移动一个正方形,如果用户想移动到另一个正方形,则必须再次按下该键。 My move method is the following: 我的移动方法如下:

public void move() {
    x += dx;
    y += dy;
}

I am using the KeyListener interface to implement the keyPressed, keyTyped and keyReleased methods and I have conditions like the one in the fragment below inside KeyPressed 我正在使用KeyListener接口来实现keyPressed,keyTyped和keyReleased方法,并且我的条件类似于KeyPressed内下面片段中的条件

//KeyPressed
int c = e.getKeyCode();

if (c == KeyEvent.VK_UP) {
    player.setDy(-5);
}

This allows the object to move freely. 这使对象可以自由移动。 However, it will clearly continue to move as long as the UP arrow is pressed. 但是,只要按下UP箭头,它显然就会继续移动。

Is there any way to have to object move up by say -5 once and then stop even if the key is still pressed? 有什么办法可以使对象说-5一次就移动,然后即使仍然按下该键也要停止吗?

I am unsure whether I need to change my move method or the KeyListener methods to do this. 我不确定是否需要更改move方法或KeyListener方法来执行此操作。

I hope that I have been clear enough as to what I'm asking and I'd highly appreciate any pointers. 我希望我对所要问的问题已经足够清楚了,对我提出的任何建议,我将深表感谢。

easiest would be to add a boolean to indicate, that a moving key is pressed 最简单的方法是添加一个布尔值,以指示按下了移动键

class member : boolean movingKeyPressed = false 类成员: boolean movingKeyPressed = false

in key pressed : 在按下的键中:

if (movingKeyPressed) {
   return;
} else {
   // do stuff
   movingKeyPressed = true;
}

in key released method : 在关键释放方法中:

movingKeyPressed = false;

first of all : you should use Synchronization if you call class-methods from within listeners like keyPressed or keyReleased - thats because your listener-method can be called from multiple threads so your class-method ( player.setDy() ) can (and will) be called in parallel - you will need to make sure that each call to setDy happens before the next one. 首先:如果您从诸如keyPressedkeyReleased之类的侦听器中调用类方法,则应该使用Synchronization-那是因为可以从多个线程调用侦听器方法,因此您的类方法( player.setDy() )可以(并且将)被并行调用-您需要确保每次调用setDy都在下一个调用之前进行。

Also : keyTyped is much better in many cases : https://stackoverflow.com/a/7071810/351861 另外: keyTyped在许多情况下要好得多: https : keyTyped

An example could look like this: 一个示例可能如下所示:

public void keyTyped(KeyEvent arg0) {
   if(arg0.getKeyCode() == KeyEvent.VK_UP)
   {
       synchronized(player)
       {
          player.setDy(-5);
       }
   }
}

this will call setDy sequentially and reliably. 这将顺序可靠地调用setDy Now all you need to do is to make sure that setDy works as intended, hence sets the position only once 现在您需要做的就是确保setDy可以按预期工作,因此仅设置一次位置

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

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