简体   繁体   English

在带有Scene2D的LibGDX中,当按下按钮时,如何连续向右行走?

[英]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: 现在的情况:

  • Hold down key -> move (just) 1 unit to the right 按住键->向右移动(仅)1个单位
  • Let go of key -> nothing happens 放开钥匙->什么也没发生

Desired situation: 期望的情况:

  • Hold down key -> move 1 unit to the right continuously 按住键->连续向右移动1个单位
  • Let go of key -> stop moving to the right 松开键->停止向右移动

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.

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