LibGDX How to get mouse coordinates in the world?

Viewed 36

I've been looking for an answer for a long time, but I can't find it. I use:

public Vector2 getWorldPositionFromScreen(Vector3 v){
    Vector3 vc = orthographicCamera.unproject(v);
    return new Vector2(vc.x, vc.y);
}

But the problem is that the y coordinate is flipped and I don't know how to flip it back. I tried the following methods, but none of them worked:

public Vector2 getWorldPositionFromScreen(Vector3 v){
    int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
    Vector3 vc = orthographicCamera.unproject(new Vector3(v.x, screenHeight - v.y, v.z));
    return new Vector2(vc.x, vc.y);
}

I tried debugging and realized that Gdx.input.getX() and ...getY() return coordinates relative to the window, not the screen enter image description here but nevertheless camera.unproject copes with this, in addition to vertical inversion. But I figured out that the inversion comes from Gdx.input.getY()

1 Answers

I don't know why, but it worked. The code I am using:

@Override
public void render(){
    
    Vector3 mouseAtScreen = new Vector3(Gdx.input.getX(),  Gdx.input.getY(), 0);
    Vector2 mouseAtWorld = getWorldPositionFromScreen(mouseAtScreen);
    spriteBatch.draw(cursorPointTexture, mouseAtWorld.x, mouseAtWorld.y, 5, 5);
}
public Vector2 getWorldPositionFromScreen(Vector3 v){
    Vector3 vc = orthographicCamera.unproject(new Vector3(v.x,   v.y, v.z));
    return new Vector2(vc.x, vc.y); 
}
Related