在 LibGDX 和 Scene2D 中,如何在按下按钮时连续向右走?
In LibGDX with Scene2D, how can I continuously walk to the right when a button is pressed?
我的 InputAdapter
中有以下代码:
...
@Override
public boolean keyDown (int keycode) {
if (keycode == Keybindings.KEY_RIGHT) this.player.right();
return super.keyDown(keycode);
}
@Override
public boolean keyUp (int keycode) {
if (keycode == Keybindings.KEY_RIGHT) this.player.stopMovingRight();
return super.keyUp(keycode);
}
...
而我的PlayerActor
class负责right()
和stopMovingRight()
:
...
public void right () {
this.right = true;
this.setX(this.getX() + 1f);
}
public void stopMovingRight () {
this.right = false;
}
...
现在,当我 运行 应用程序时,当我按下 KEY_RIGHT
键(键盘上的 'D' 键)时,我的 PlayerActor
仅移动 1 个单位。问题是我想 连续 在按下键的同时移动 PlayerActor
。
现在情况:
- 按住 键 -> 向右移动(仅)1 个单位
- 松开钥匙 -> 没有任何反应
期望的情况:
- 按住键->连续向右移动1个单位
- 松开键->停止向右移动
我很想听听你对这件事的看法,干杯!
您在这里遇到的问题是,keyDown()
只被调用了一次,因此您的玩家 ID 只移动了 1 个单位。您需要做的是,创建一些变量,例如 isMovingRight
并在每次游戏更新时检查它。
游戏class:
public final void render(float delta) {
...
player.update();
...
}
玩家class:
public void update() {
if(isMovingRight) {
this.setX(this.getX() + 1f);
}
}
我的 InputAdapter
中有以下代码:
...
@Override
public boolean keyDown (int keycode) {
if (keycode == Keybindings.KEY_RIGHT) this.player.right();
return super.keyDown(keycode);
}
@Override
public boolean keyUp (int keycode) {
if (keycode == Keybindings.KEY_RIGHT) this.player.stopMovingRight();
return super.keyUp(keycode);
}
...
而我的PlayerActor
class负责right()
和stopMovingRight()
:
...
public void right () {
this.right = true;
this.setX(this.getX() + 1f);
}
public void stopMovingRight () {
this.right = false;
}
...
现在,当我 运行 应用程序时,当我按下 KEY_RIGHT
键(键盘上的 'D' 键)时,我的 PlayerActor
仅移动 1 个单位。问题是我想 连续 在按下键的同时移动 PlayerActor
。
现在情况:
- 按住 键 -> 向右移动(仅)1 个单位
- 松开钥匙 -> 没有任何反应
期望的情况:
- 按住键->连续向右移动1个单位
- 松开键->停止向右移动
我很想听听你对这件事的看法,干杯!
您在这里遇到的问题是,keyDown()
只被调用了一次,因此您的玩家 ID 只移动了 1 个单位。您需要做的是,创建一些变量,例如 isMovingRight
并在每次游戏更新时检查它。
游戏class:
public final void render(float delta) {
...
player.update();
...
}
玩家class:
public void update() {
if(isMovingRight) {
this.setX(this.getX() + 1f);
}
}