44 lines
1.4 KiB
C#
44 lines
1.4 KiB
C#
using System;
|
|
using Gameplay;
|
|
using Framework;
|
|
using Gameplay.Unit;
|
|
using Gameplay.Level;
|
|
using System.Collections.Generic;
|
|
|
|
public static class NearestSearchUtils
|
|
{
|
|
public static int FindNearestIndex<T>(GameUnit owner, List<T> list, Func<T, int> getCellIndexFunc)
|
|
{
|
|
try
|
|
{
|
|
var map = LevelManager.Instance.CurrentLevel?.Map;
|
|
if (owner == null || map == null || list == null || list.Count == 0)
|
|
return Constants.INVALID_ID;
|
|
|
|
var ownerCellIndex = owner.transData?.cellIndex ?? Constants.INVALID_ID;
|
|
if (ownerCellIndex == Constants.INVALID_ID)
|
|
return Constants.INVALID_ID;
|
|
|
|
var nearestIndex = 0;
|
|
var minDistance = int.MaxValue;
|
|
|
|
for (var i = 0; i < list.Count; i++)
|
|
{
|
|
var targetCellIndex = getCellIndexFunc(list[i]);
|
|
if (targetCellIndex == Constants.INVALID_ID) continue;
|
|
|
|
var distance = MapUtils.Distance(map, ownerCellIndex, targetCellIndex);
|
|
if (distance >= minDistance) continue;
|
|
minDistance = distance;
|
|
nearestIndex = i;
|
|
}
|
|
|
|
return nearestIndex;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
DebugUtil.LogError("NearestSearchUtils.FindNearestIndex error: {0}", e);
|
|
return 0;
|
|
}
|
|
}
|
|
} |