不知道如何表达标题。
我有一些“太空入侵者”类型游戏的代码。我只是做了一些调整才完成了整个事情。为了拍摄,我使用空格键。问题是我无法按住空格键并且它会不断射击。我宁愿必须多次按下它(如果我按住它......为了它不会连续触发)我将如何改变它?
*这是我认为是问题根源的代码。如果来源位于其他地方,请注明。
private class KeyInputHandler extends KeyAdapter {
private int pressCount = 1;
/**
* key pressed
*/
public void keyPressed(KeyEvent e) {
if (waitingForKeyPress) {
return;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = true;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
firePressed = true;
}
}
/**
* Key Released
*/
public void keyReleased(KeyEvent e) {
if (waitingForKeyPress) {
return;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
firePressed = false;
}
}
添加代码
public class ShotEntity extends Entity {
//vertical speed
private double moveSpeed = -300;
private Game game;
private boolean used = false;
/**
* Create a new shot from the player
*/
public ShotEntity(Game game,String sprite,int x,int y) {
super(sprite,x,y);
this.game = game;
dy = moveSpeed;
}
/**
* Request that this shot moved based on time
*/
public void move(long delta) {
super.move(delta);
if (y < -100) {
game.removeEntity(this);
}
}
//collision
public void collidedWith(Entity other) {
// prevents double kills.
if (used) {
return;
}
// alien killed
if (other instanceof AlienEntity) {
game.removeEntity(this);
game.removeEntity(other);
game.notifyAlienKilled();
used = true;
}
}
}
最佳答案
监听两个单独的关键事件。按下该键时为一,释放时为一。现在,您创建一个 boolean 值。
公共(public) boolean myBoolean;
当按下按键时,将 boolean 值设置为 true (myBoolean==true
),如果松开,将其设置为 false (myBoolean==false
)。
现在,创建一个简单的 if 语句:
if(myBoolean==true){ //Key is being held down
//execute this code
//Have nothing be done
}
就是这样!
附注如果需要,您可以使用一种单独的方法来清理代码。此方法只能更改 boolean 值:
public void changeValueOfBoolean(Boolean b){
if(b = true){
return false;
}
if(b==false){
return true;
}
}
这很简单。如果您需要任何帮助,请告诉我,如果这有帮助,请将其标记为最佳答案。有任何问题请随时问我,我很乐意提供帮助!
说明:
好的,我们有了这个 boolean 值,对吧?现在,这个 boolean 值本质上决定了是否按下该键。
假设我们按下按钮:
因为按键被按住,所以我们将 boolean 值 myBoolean
设置为 true。现在,因为用户按住了按键,所以我们什么都不想做,对吧?这就是我们创建 if 语句的原因:
if(myBoolean==true){ //Key is being held down
//execute this code
//Have nothing be done
}
它说,如果 boolean 值为真,那么我们不会做任何事情。回想一下,当按住按键时 boolean 值为 true,还记得吗?因此,当按住该键时, boolean 值为 true,并且不会执行任何操作。
现在,当用户释放 key 时:
现在,假设用户已按下该键。这将调用两个监听器。一个监听器监听按键被按下的时间,另一个监听器监听按键释放的时间。如果用户只是按下该键,则 myBoolean 将以 false 结束,因为他们已经松开了该键。因此,我们可以在 myBoolean 为 false 时执行一些代码(射击)。
**总结:
myBoolean
当按键被按住时为 true。所以,当它是真的时,我们什么也不做。当用户放开按键时,myBoolean
为 false,然后我们射击太空入侵者。**
关于java - 调整按下的按键,这样就不能 "Hold"it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33711030/