首页 > 解决方案 > Java - Libgdx -TiledMap | 为地图中的每个单元格获取 screenX 和 screenY

问题描述

正如标题所说,我正在尝试获取地图中每个单元格的屏幕坐标。有可能吗?我真的很沮丧,想不通!我感谢您的帮助!请注意,我的地图在屏幕上有一个静态位置。

另一个注意事项:我有一个扩展 Actor 的自定义类 Cell。我让它使我的单元格可点击,它看起来像这样:

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)));

谢谢!!

标签: javalibgdxgame-developmenttiledtmxtiledmap

解决方案


你可以这样处理:

在您的 Cell 类中添加一个新变量以获取图块的位置。

    private Vector2 pos;

更改您的构造函数。

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

在您的主类中获取地图宽度中的图块数量,对图块的高度和大小执行相同操作。

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

现在使用循环

    // 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;
        }
    }   

这是我使用的方法,因为我没有找到任何其他方法。


推荐阅读