Search code examples
javaimagelibgdxlistener

libgdx how to add clicklistener at images


I just started to prototype with libGDX to understand how it works. I want to realize a grid (like chess game) and when I click/touch a box of the grid, this change its image.

I've found a good tutorial, but it only use the keyboard listener and on web I can't find a good example that clarify to me the these mechanics.

What i don't understand is essentially: what use to render the boxes (for now I've used only SpriteBatch and ShapeRenderer) and how detect when e which box was clicked (I think that calculate coordinates not was a good way to follow. I imagine that best way is add a click listener at each box to determine when it will clicked, but I don't know how to code this).

Thanks for any suggestion, if you have an example, it can help me a lot.


Solution

  • Image image = new Image();
    
    image.addListener(new ClickListener(){
        @Override
        public void clicked(InputEvent event, float x, float y) {
            System.out.println("You clicked an image...");
        }
    });
    

    Now we can add this image to something like a Table or directly to the Stage.

    Like dtx12 has mentioned you should look into Scene2D. You probably want to setup a grid using a table like so.

    Table chessTable = new Table();
    int boardHeight = 8;
    int boardWidth = 8;
    
    for (int y = 0; y < boardHeight; y++)
    {
        for (int x = 0; x < boardWidth; x++)
        {
            //Check if dividable by two to make checker pattern and add cell to table.
            if (x + y % 2 == 0)
                chessTable.add(blackImage);
            else 
                chessTable.add(whiteImage);
        }
        //Add a new row to table
        chessTable.row();
    }