Search code examples
javalibgdx

Libgdx cursor disappears after catched


I set the mouse to be "catched" with

Gdx.input.setCursorCatched(true);

but the cursor disappeared with this setting on. I'm developing an isometric 2d rts game and I really need the cursor to be forced to stay inside the window but I also obviously need the cursor to be shown. I'm using a Tiled map to draw the map.


Solution

  • I have a game where I draw a dot wherever/whenever the player touches down or touches up, if you catch the cursor it will disappear, it's intended behavior.

    To fix this you have to draw a mouse yourself using a Texture, Sprite or TextureRegion. Here's an example:
    To draw the cursor:

    public class MyCursor {
    
        private TextureRegion cursor;
        private float x, y;
    
        public MyCursor(TextureRegion cursorRegion) {
            cursor = cursorRegion;
        }
    
        public void render(SpriteBatch spriteBatch) {
            spriteBatch.begin();
            spriteBatch.draw(cursor, x, y);
            spriteBatch.end();
        }
    
        public void setPosition(float x, float y) {
            this.x = x;
            this.y = y;
        }
    }
    

    To process input:

    public class MyInput extends InputAdapter {
    
        private OrthographicCamera camera;
        private MyCursor myCursor;
    
        public MyInput(OrthographicCamera camera, MyCursor myCursor) {
            this.camera = camera;
            this.myCursor = myCursor;
        }
    
        @Override
        public boolean mouseMoved(int screenX, int screenY) {
            Vector3 temp = camera.unproject(new Vector3(screenX, screenY, 0));
            myCursor.setPosition(temp.x, temp.y);
            return true;
        }
    }
    

    Also don't forget to enable input:

    public class MyGame extends Game {
    
        @Override
        public void create() {
            OrthographicCamera camera = new OrthographicCamera();
            TextureRegion cursorRegion = new TextureRegion(new Texture("myCursor.png"));
            MyCursor cursor = new MyCursor(cursorRegion);
            MyInput myInput = new MyInput(camera, cursor);
            Gdx.input.setInputProcessor(myInput);
        }
    }