Reputation: 197
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.
Upvotes: 2
Views: 3323
Reputation: 8584
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();
}
Upvotes: 4
Reputation: 4488
Scene2d is the best for your purposes, check documentation. https://github.com/libgdx/libgdx/wiki/Scene2d
You may add ActorGestureListener
to created actor for example.
For rendering something using ShapeRenderer
you may override actor's draw
method
and apply matrix to them. But would be better to have simple image with rectangle instead of using ShapeRenderer
if you only need to draw boxes. Select variant which you like more.
Upvotes: 0