[英]In LibGDX with Scene2D, how can I continuously walk to the right when a button is pressed?
I have the following piece of code in my InputAdapter
: 我的
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);
}
...
And my PlayerActor
class is responsible for right()
and stopMovingRight()
: 我的
PlayerActor
类负责right()
和stopMovingRight()
:
...
public void right () {
this.right = true;
this.setX(this.getX() + 1f);
}
public void stopMovingRight () {
this.right = false;
}
...
Now, when I run the application, my PlayerActor
moves just 1 unit when I press the KEY_RIGHT
key (the 'D' key on the keyboard). 现在,当我运行该应用程序时,当我按下
KEY_RIGHT
键(键盘上的“ D”键)时,我的PlayerActor
仅移动1个单位。 The problem is that I instead want to continuously move the PlayerActor
while I am pressing down the key. 问题是我想在按下键的同时连续移动
PlayerActor
。
Situation now: 现在的情况:
Desired situation: 期望的情况:
I would love to hear your thoughts on this matter, cheers! 我很想听听您对此事的想法,欢呼!
The problem you encourted here is, that keyDown()
is called only once, therefore your player id moved only by 1 unit. 您在此处提出的问题是
keyDown()
仅被调用一次,因此您的播放器ID仅移动了1个单位。 What you need to do is, create some variable, for example isMovingRight
and check it every time the game is updated. 您需要做的是创建一个变量,例如
isMovingRight
并在每次游戏更新时检查它。
Game class: 游戏类别:
public final void render(float delta) {
...
player.update();
...
}
Player class: 玩家等级:
public void update() {
if(isMovingRight) {
this.setX(this.getX() + 1f);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.