LibGDX:在一个单独的类中创建一个GestureListener

时间:2017-01-10 06:15:54

标签: java android libgdx

我目前有一个类可以处理我想要的所有手势,它看起来像这样:

public class InputHandler  implements GestureDetector.GestureListener{

  private Player myPlayer;

  public InputHandler(Player player){
    myPlayer = player;
  }

  @Override
  public boolean touchDown(float x, float y, int pointer, int button) {
    return false;
  }

  @Override
  public boolean tap(float x, float y, int count, int button) {
    return false;
  }

  @Override
  public boolean longPress(float x, float y) {
    return false;
  }

  @Override
  public boolean fling(float velocityX, float velocityY, int button) {
    if(velocityY > 0){
      myPlayer.onSwipeUp();
    }
    return false;
  }

  @Override
  public boolean pan(float x, float y, float deltaX, float deltaY) {
    return false;
  }

  @Override
  public boolean panStop(float x, float y, int pointer, int button) {
    return false;
  }

  @Override
  public boolean zoom(float initialDistance, float distance) {
    return false;
  }

  @Override
  public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) {
    return false;
  }

  @Override
  public void pinchStop() {

  }
}

正如你所看到的,我使用的唯一方法是“fling”方法但是我想在我的'MainScreen'类中创建Gesture监听器,因为它包含对'myPlayer'的引用,我希望它通过进入这个类,但我不知道如何创建监听器。到目前为止,我在构造函数中有这个:

public class GameScreen implements Screen {

  private GameWorld world;
  private GameRenderer renderer;
  GestureDetector gd;


  public GameScreen(){
    float screenWidth = Gdx.graphics.getHeight();
    float screenHeight = Gdx.graphics.getWidth();
    float gameWidth = 816;
    float gameHeight = screenHeight/(screenWidth/gameWidth);

    int midpointY = (int)(gameHeight/2);

    world = new GameWorld(midpointY);
    renderer = new GameRenderer(world);

    gd = new GestureDetector(new myGestureListener(world.getPlayer())); //Error here, 'myGestureListener' cannot be resolved
    Gdx.input.setInputProcessor(gd);



  }

我知道'myGestureListener'从未被创建过,因此无法解决,但我对如何修复此错误同时确保正确传递引用感到困惑。如果我需要初始化GestureListener,我该怎么做?

如果这个问题毫无意义或者没有解决方案,我提前道歉,我仍然不熟悉使用libGDX框架进行编码。

2 个答案:

答案 0 :(得分:1)

您没有名为myGestureListener的课程?

从您的问题来看,您似乎将其称为InputHandler,因此您可能使用了错误的名称。

答案 1 :(得分:0)

InputHandler是你的GestureListener实现的类,所以make该类的对象并在GestureDetector构造函数中作为参数传递。

public class GameScreen implements Screen {

  private GameWorld world;
  private GameRenderer renderer;
  private GestureDetector gd;

  public GameScreen(){
    float screenWidth = Gdx.graphics.getHeight();
    float screenHeight = Gdx.graphics.getWidth();
    float gameWidth = 816;
    float gameHeight = screenHeight/(screenWidth/gameWidth);

    int midpointY = (int)(gameHeight/2);

    world = new GameWorld(midpointY);
    renderer = new GameRenderer(world);

    gd = new GestureDetector(new InputHandler(world.getPlayer())); 
    Gdx.input.setInputProcessor(gd);
  }