Files
daluandou/Assets/Script/DeployGrid.cs
T
huadexuan 1abd0de32f ```
feat(player): 添加玩家阵型保存功能

新增savedFormation字段用于存储玩家的阵型配置,
包括角色ID列表和对应的格子索引位置信息。
```
2026-09-29 23:21:44 +08:00

70 lines
2.9 KiB
C#

using UnityEngine;
/// <summary>
/// 部署网格的几何参数与坐标换算。
/// 阵型编排场景和战斗场景共用同一份参数,保证两边的格位完全对齐。
/// </summary>
public static class DeployGrid
{
public const int Cols = 6;
public const int Rows = 5;
public const float ColStep = 2.4f; // 列间距改为2.4,让网格更紧凑,避免最边缘格子太靠外
public const float RowStep = 2.8f; // 行间距保持2.8
public const float BackZ = -15.0f; // 最靠后一排的中心 Z(调整到靠近摄像机的底部区域)
public const float CellWidth = 2.5f;
public const float CellDepth = 2.5f; // 格子深度改为2.5,与宽度相同,形成正方形
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;
/// <summary>格位中心的世界坐标(单位落点高度)。</summary>
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);
}
/// <summary>把地面上的世界坐标吸附到最近格位;不在网格范围内返回 -1。</summary>
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);
}
/// <summary>把一组单位在网格宽度内均匀铺开,返回列号。</summary>
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));
}
/// <summary>默认阵型格位:近战在最前排(靠近敌人),远程在最后排。</summary>
public static int DefaultCell(bool isMelee, int indexInGroup, int groupCount)
{
int row = isMelee ? Rows - 1 : 0;
return ToIndex(row, SpreadColumn(indexInGroup, groupCount));
}
}