using UnityEngine; /// /// 部署网格的几何参数与坐标换算。 /// 阵型编排场景和战斗场景共用同一份参数,保证两边的格位完全对齐。 /// public static class DeployGrid { public const int Cols = 6; public const int Rows = 5; public const float ColStep = 2.8f; public const float RowStep = 3.0f; public const float BackZ = 2.5f; // 最靠后一排的中心 Z(让部署区落在底部卡片栏上方) public const float CellWidth = 2.5f; public const float CellDepth = 2.7f; public const float CellHeight = 0.03f; public const float GridY = 0.12f; // 格位可视块的中心高度 public const float UnitY = 0.16f; // 单位落点高度(与 NavMesh 高度一致) public const int CellCount = Cols * Rows; public static int ToIndex(int row, int col) => row * Cols + col; public static int RowOf(int index) => index / Cols; public static int ColOf(int index) => index % Cols; public static bool IsValidIndex(int index) => index >= 0 && index < CellCount; /// 格位中心的世界坐标(单位落点高度)。 public static Vector3 CellPosition(int index) { int r = RowOf(index); int c = ColOf(index); float x = (c - (Cols - 1) * 0.5f) * ColStep; float z = BackZ + r * RowStep; return new Vector3(x, UnitY, z); } /// 把地面上的世界坐标吸附到最近格位;不在网格范围内返回 -1。 public static int SnapToCell(Vector3 world) { int c = Mathf.RoundToInt(world.x / ColStep + (Cols - 1) * 0.5f); int r = Mathf.RoundToInt((world.z - BackZ) / RowStep); if (c < 0 || c >= Cols || r < 0 || r >= Rows) { return -1; } Vector3 center = CellPosition(ToIndex(r, c)); if (Mathf.Abs(center.x - world.x) > ColStep * 0.5f) return -1; if (Mathf.Abs(center.z - world.z) > RowStep * 0.5f) return -1; return ToIndex(r, c); } /// 把一组单位在网格宽度内均匀铺开,返回列号。 public static int SpreadColumn(int indexInGroup, int groupCount) { if (groupCount <= 1) return Cols / 2; if (groupCount >= Cols) return indexInGroup % Cols; float step = (Cols - 1f) / (groupCount + 1f); return Mathf.RoundToInt(step * (indexInGroup + 1)); } /// 默认阵型格位:近战在最前排(靠近敌人),远程在最后排。 public static int DefaultCell(bool isMelee, int indexInGroup, int groupCount) { int row = isMelee ? Rows - 1 : 0; return ToIndex(row, SpreadColumn(indexInGroup, groupCount)); } }