'use strict'; /** 与 Unity PPU=100、Grid CellSize (1,0.5,1) 一致(世界坐标 Y 向上) */ const CELL_PIXEL = 100; const HALF_W = CELL_PIXEL * 0.5; const HALF_H = CELL_PIXEL * 0.25; const PANEL_HALF_W = HALF_W; const PANEL_HALF_H = HALF_H; function worldToCellXY(wx, wy) { const cx = (wy / HALF_H + wx / HALF_W) * 0.5; const cy = (wy / HALF_H - wx / HALF_W) * 0.5; return { x: Math.round(cx), y: Math.round(cy) }; } /** 世界坐标为格子中心时 → 格子索引(与 cellCenterCanvas 互逆) */ function worldCenterToCellXY(wx, wy) { return worldToCellXY(wx, wy - HALF_H); } function cellToWorldXY(cx, cy) { return { x: (cx - cy) * HALF_W, y: (cx + cy) * HALF_H, }; } function cellCenterWorldXY(cx, cy) { const w = cellToWorldXY(cx, cy); return { x: w.x, y: w.y + HALF_H }; } function cellKey(x, y) { return `${x},${y}`; } /** 世界坐标 → Canvas(Y 向下,与 Unity/Cocos 预览一致) */ function worldToCanvasXY(wx, wy, offsetX, offsetY) { return { x: offsetX + wx, y: offsetY - wy, }; } /** 格子底顶点(Grid.CellToWorld) */ function cellAnchorCanvas(cx, cy, offsetX, offsetY) { const w = cellToWorldXY(cx, cy); return worldToCanvasXY(w.x, w.y, offsetX, offsetY); } /** 格子中心(Unity Tilemap m_TileAnchor 0.5,0.5 → 精灵 pivot 对齐点) */ function cellCenterCanvas(cx, cy, offsetX, offsetY) { const w = cellToWorldXY(cx, cy); return worldToCanvasXY(w.x, w.y + HALF_H, offsetX, offsetY); } /** 鼠标拾取:与贴图 pivot 相同,使用格子中心(worldCenterToCell) */ function cellFromCanvas(mx, my, offsetX, offsetY) { const wx = mx - offsetX; const wyCenter = offsetY - my; const c = worldCenterToCellXY(wx, wyCenter); return { x: c.x, y: c.y, key: cellKey(c.x, c.y) }; } function cellToCanvas(cx, cy, offsetX, offsetY) { const a = cellAnchorCanvas(cx, cy, offsetX, offsetY); return { px: a.x, py: a.y }; } module.exports = { CELL_PIXEL, HALF_W, HALF_H, PANEL_HALF_W, PANEL_HALF_H, worldToCellXY, worldCenterToCellXY, cellToWorldXY, cellCenterWorldXY, cellKey, worldToCanvasXY, cellAnchorCanvas, cellCenterCanvas, cellFromCanvas, cellToCanvas, };