Reputation: 79
currently I'm trying to create a Sudoku game based on images. What I'm trying to figure out now is what cell was clicked to send that signal to the logic of my game. This is how I've created the UI for the board:
private void initGrid(){
String value = new String();
for (int i = 0; i<9; i++){
for (int j = 0; j<9; j++){
value = MathUtils.random(1, 9)+"";
this.grid[i][j] = new Image(atlas.findRegion(value));
this.grid[i][j].setScale(0.5f);
this.grid[i][j].setPosition(i * 64 + padX, GameConstants.screenHeight - (j * 64 + padY));
this.grid[i][j].setOrigin(ImgHeight / 2, ImgWidth / 2);
this.grid[i][j].setAlign(Align.center);
this.grid[i][j].addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y){
System.out.println("Image clicked: "+x+" "+y);
}
});
stage.addActor(this.grid[i][j]);
}
}
}
What I get instead is something from 0 to 128 on both axis on each cell, even though I'm drawing them at 0.5 scale. I'm not getting an absolute position. I would like to get something like i = 0-8, j = 0-8. I'm not drawing on a table because it has some scale animations and didn't work out.
Upvotes: 0
Views: 59
Reputation: 1376
You can use the setName(String) method of the Image to store the image grid location
this.grid[i][j] = new Image(atlas.findRegion(value));
this.grid[i][j].setName(i+":"+j);
Then in the listener can output the image name with
this.grid[i][j].addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y){
System.out.println(event.getListenerActor().getName());
}
});
This should print out something like 0:0 to 8:8
Upvotes: 1
Reputation:
Well, yes - it won't return the position in the grid, because it doesn't know about the grid itself. If you're just interested in Image object, then you should be able to get it by casting source of event into Image.
Image source = (Image)event.getSource();
On the other hand, if you really need indexes - for example to replace it in grid, you will have to loop through grid and compare them.
Upvotes: 1