我在cocos 中导入了45度 tiledmap地图,然后想把地图中没有瓦片的网格标记出并且显示,但是标记出来的点坐标似乎有微小偏差,以下是我的代码和效果图,请各位大佬帮忙看一下,问题出在哪里,如果允许的话,可以把这个测试一下。
/**
*标记地图layer(名字为no)中不存在障碍物的网格
*/
markEmptyGrids() {
const mapSize = this.tiledMap.getMapSize();
const tileSize = this.tiledMap.getTileSize();
// 遍历所有图层
const layer = this.tiledMap.getLayer("no");
for (let row = 0; row < mapSize.height; row++) {
for (let col = 0; col < mapSize.width; col++) {
const tile = layer.getTileGIDAt(col, row);
if (!tile) {
this.createRedMarker(col, row, tileSize);
}
}
}
}
private createRedMarker(col: number, row: number, tileSize: Size) {
const marker = instantiate(this.gridNode);
marker.parent = this.node.getChildByName("mapastar");
const pos = this.calculateGridPosition(col, row);
marker.setPosition(new Vec3(pos.x, pos.y, 0));
// 强制匹配瓦片尺寸 0.9是留的缝隙 方便观察 并没有影响实际效果
marker.width = tileSize.width * 0.9; //tileSize.width 64
marker.height = tileSize.height * 2 * this.tileHeightRatio * 0.9; // tileSize.height 32 this.tileHeightRatio是0.5
}
/**
-
修正后的45°视角坐标计算
-
重点解决Tiled与Cocos Creator的坐标系差异
*/
calculateGridPosition(col: number, row: number): Vec2 {
const tileSize = this.tiledMap.getTileSize();
const mapSize = this.tiledMap.getMapSize();
// 地图总高度(用于补偿锚点偏移)
const totalHeight = mapSize.height * tileSize.height;
// 基础菱形坐标转换公式
let x = (col - row) * (tileSize.width / 2);
let y =
mapSize.height * tileSize.height -
(col + row) * (tileSize.height / 2) -
totalHeight / 2;
return v2(x, y);
}
