简体   繁体   中英

Java - Libgdx -TiledMap | get screenX & screenY for every Cell in the Map

as the title says, i'm trying to get the screen coordinates for each cell in my map. is it even possible? I'm really frustraited and can't figure it out! I appreciate your help! note that my map has a static position on the screen.

Another note: i have a custom class Cell that extends Actor. I made it to make my cells clickable and it looks like this:

public class Cell extends Actor {
private TiledMapTileLayer.Cell tiledMapCell;
private Texture cellTexture;

public Cell(TiledMapTileLayer.Cell tiledMapCell, Field field){
    this.tiledMapCell = tiledMapCell;
    this.field = field;
    this.cellTexture = tiledMapCell.getTile().getTextureRegion().getTexture();
}

public TiledMapTileLayer.Cell getTiledMapCell(){
    return this.tiledMapCell;
}

public Texture getCellTexture(){
    return this.cellTexture;
}

public void setCellTexture(Texture texture){
    this.cellTexture = texture;
    this.tiledMapCell.setTile(new StaticTiledMapTile(new TextureRegion(cellTexture)));

Thanks!!

You can process like this :

In your Cell class add a new Variable to get the position of the tile.

    private Vector2 pos;

Change your constructor.

    public Cell(TiledMapTileLayer.Cell tiledMapCell, Field field, Vector2 pos) {
        this.tiledMapCell = tiledMapCell;
        this.field = field;
        this.cellTexture = tiledMapCell.getTile().getTextureRegion().getTexture();
        this.pos = pos;
    }

In your main class get the number of tiles in the width of your map, do the same for the height and the size of a tile.

    int mapWidth = tiledMapTileLayer.getWidth();
    int mapHeight = tiledMapTileLayer.getHeight();
    int tileSize = tiledMapTileLayer.getTileWidth();

now use a loop

    // These variables will store the coordinates of each new tile. and will be changed at each loop turn.
    int tempX = 0;
    int tempY = 0;

    for (int i = 0; i < mapWidth * mapHeight; i++) {
        pos = new Vector2 (tempX + tileSize / 2, tempY + tileSize / 2);

        // Create a new cell with your Cell class, pass it the position.    
        new Cell(TiledMapTileLayer.Cell tiledMapCell, Field field, pos)

        // Increase the tempX
        tempX += tileSize;
        // If the first line is finish we go to the next one.
        if (tempX > mapWidth * tileSize) {
            tempY += tileSize;
            tempX = 0;
        }
    }   

This is the method i use cause i did not find any other way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM