Search code examples
javalibgdx

Mouse coordinates offset compensation issue for sprite under pointer on left-clicking


i am trying to get a sprite to move to my mouse coordinates, and i am having luck, although limited. i have the following code that makes it so the sprite is moving, but it still isn't moving to where i am clicking, just relative to it. it seems that the code i found online offsets the Y position of the mouse (subtracts) but not the X? I wonder why? thanks

if(Gdx.input.isButtonPressed(Input.Buttons.LEFT)){
        sprite.setPosition(Gdx.input.getX() - sprite.getWidth()/2,
                Gdx.graphics.getHeight() - Gdx.input.getY() - sprite.getHeight()/2);
};

Solution

  • The coordinates of the mouse input are relative to the top left corner of the screen. So you must calculate the position of the mouse in the world based on the camera position and his origin.

    You can do this manually or I found on this site:

        Vector3 worldCoordinates = new Vector3(x, y, 0);
        camera.unproject(worldCoordinates);
    

    The reason why in the code Gdx.graphics.getHeight() - Gdx.input.getY() - sprite.getHeight()/2 is used for the y position is, that the Worlds Y is growing up but the mouse Y is growing down.