使用输入处理器libgdx移动精灵

时间:2013-09-04 06:44:06

标签: java input libgdx

我正在使用一个名为InputHandler的类来实现InputPorcessor。但是我遇到了一个问题,我无法通过点击屏幕将玩家移动到我选择的位置。

原因是因为我不确定如何在地图上协调x,y然后用来设置玩家的新位置。

这是我的InputHandler类

public class InputHandler implements InputProcessor {

    private OrthographicCamera cam;

    private boolean dragged = false;

    private Player player;

    private TiledMap map;

    private Vector2 oPos;

    public InputHandler(OrthographicCamera camera, Player player,
            TiledMap map) {
        this.cam = camera;
        this.player = player;
        this.map = map;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer,
            int button) {
        oPos = new Vector2(Gdx.input.getX(), Gdx.input.getY());
        return false;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer,
            int button) {
        if (!dragged) {
            // move the player
        } else
            dragged = false;
        return false;
    }

    public boolean touchDragged(int x, int y, int pointer) {
        dragged = true;
        moveCamera(x, y);
        return false;
    }

    private void moveCamera(int touchX, int touchY) {
        Vector2 nPos = getNewCameraPosition(touchX, touchY);

        cam.translate(nPos.sub(cam.position.x, cam.position.y));
        Gdx.app.log(PArena.LOG, "Moved Camera");

        oPos.set(touchX, touchY);
    }

    private Vector2 getNewCameraPosition(int x, int y) {
        Vector2 nPos = oPos;
        nPos.sub(x, y);
        nPos.y = -nPos.y;
        nPos.add(cam.position.x, cam.position.y);
        return nPos;
    }
}

1 个答案:

答案 0 :(得分:1)

要了解您的游戏世界(通过Camera查看),您需要使用此代码段:

Vector3 screenTouchPosition= new Vector3(touchX, touchY, 0);
cam.unproject(screenTouchPosition); // this will change your Vector directly
Vector3 gameWorldTouchPosition = screenTouchPosition;