Search code examples
javalibgdx

Input not grabbing correct coordinate libgdx java


I am making a mining game where if you click somewhere you will delete the block laying there. All blocks right now are just squares and are only drawn if the spot in my 2d boolean array is true. So I am trying to take the position and set it to false wherever you click here is the touchdown method of my inputprocessor

    private Vector2 tmp = new Vector2();
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    tmp.x = screenX / MapGrid.CELL_SIZE;
    tmp.y = screenY / MapGrid.CELL_SIZE;
    cam.unproject(new Vector3(tmp.x, tmp.y, 0));
    grid.manipulateGrid((int)(tmp.x), (int)(tmp.y), false);
    System.out.println("Clicked at: (" + tmp.x + ", " + tmp.y +")");
    return false;
}

I am also translating the camera to my players position. The grid.manipulateGrid takes an x and a y and sets it to false. My player is located at (10, 126) in grid coordinates and when I click next to him it says I am clicking at (35, 24) I am not sure if I am doing this right but I have been really searching everywhere and can't find a solution. I have found questions similar but to not result. If someone can tell me how to adjust the click to the coordinates of the player I would be incredibly appreciative.


Solution

  • You have to divide the mapgrid after unprojecting it

        @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        tmp.x = screenX;
        tmp.y = (Gdx.graphics.getHeight() - screenY);
        tmp.z = 0;
        cam.unproject(tmp);
        grid.manipulateGrid((int)(tmp.x) / MapGrid.CELL_SIZE, (int)(tmp.y) / MapGrid.CELL_SIZE, false);
        System.out.println("Clicked at: (" + tmp.x / MapGrid.CELL_SIZE + ", " + tmp.y / MapGrid.CELL_SIZE +")");
        return false;
    }