使用输入处理器使对象跟随触摸输入的x轴,对象变得疯狂

时间:2015-08-17 11:59:55

标签: java libgdx

所以我想要它,以便当用户触摸屏幕时,对象遵循触摸屏的x轴。当我通过轮询(Gdx.input.getX())执行此操作时,它就像它必须的那样工作。但是对于输入处理器,当触摸屏幕时,对象在整个屏幕上都会发疯。我真的不明白为什么。这是代码

Player.java:

public class Player extends Entity
{
    MyInputProcessor input;

    public Player(float x, float y, Sprite sprite)
    {
        super(x, y, sprite);
        input = new MyInputProcessor();
        Gdx.input.setInputProcessor(input);
    }

    public void update(final Application app)
    {
        handleInput(app);
        super.update();
    }

    public void handleInput(Application app)
    {
        if (input.touchDown)
        {
            Vector2 touchPos = app.viewport.unproject(input.screenTouchPos);
            position.x = touchPos.x - sprite.getWidth() / 2;
        }
    }
}

MyInputProcessor.java:

public class MyInputProcessor implements InputProcessor
{
    public boolean touchDown = false;
    public Vector2 screenTouchPos;

    public MyInputProcessor()
    {
        screenTouchPos = new Vector2();
    }

    @Override
    public boolean keyDown(int keycode)
    {
        return false;
    }

    @Override
    public boolean keyUp(int keycode)
    {
        return false;
    }

    @Override
    public boolean keyTyped(char character)
    {
        return false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button)
    {
        touchDown = true;
        screenTouchPos.set(screenX, screenY);
        return false;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button)
    {
        touchDown = false;
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer)
    {
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY)
    {
        return false;
    }

    @Override
    public boolean scrolled(int amount)
    {
        return false;
    }
}

1 个答案:

答案 0 :(得分:2)

这一行

Vector2 touchPos = app.viewport.unproject(input.screenTouchPos);

不会为您提供未投影的矢量的副本。它正在修改输入Vector2并将您返回相同的参考。由于您的输入处理器仅在您触摸时重置其Vector2,因此只要您按住手指,您的Player类将在每个帧上取消投影相同的矢量。不止一次在同一个向量上调用unproject显然会开始产生垃圾结果。

相反,请为此保留额外的Vector 2。

private final Vector2 unprojectedTouchPos = new Vector2();

然后将触摸位置矢量复制到每个帧的此向量中,并使用此向量:

public void handleInput(Application app)
{
    if (input.touchDown)
    {
        unprojectedTouchPos.set(input.screenTouchPos);
        app.viewport.unproject(unprojectedTouchPos);
        position.x = unprojectedTouchPos.x - sprite.getWidth() / 2;
    }
}

修改 根据您的评论,您还希望该位置在手指拖动时实时更新,因此将其添加到您的InputProcessor的touchDragged方法中:

screenTouchPos.set(screenX, screenY);