Оптимизация кода C# , вычисление расстояния между объектами
Всем привет. Есть код, который находит наименьшее расстояние между объектами и выбирает объект для дальнейшего взаимодействия в игре.
Вижу и знаю, что код выглядит ужасно, но не понимаю, как его сократить правильно (например с помощью foreach).
Прошу помощи, не обижайте только)
код:
void Distanse()
{
if (bots[0] != null)
{
if (players[0] != null)
{
float tmp1 = Vector3.Distance(players[0].transform.position, bots[0].transform.position);
if (tmp1 < distance)
{
distance = tmp1;
botNearest = bots[0];
}
}
if (players[1] != null)
{
float tmp1 = Vector3.Distance(players[1].transform.position, bots[0].transform.position);
if (tmp1 < distance)
{
distance = tmp1;
botNearest = bots[0];
}
}
if (players[2] != null)
{
float tmp1 = Vector3.Distance(players[2].transform.position, bots[0].transform.position);
if (tmp1 < distance)
{
distance = tmp1;
botNearest = bots[0];
}
}
}
if (bots[1] != null)
{
if (players[0] != null)
{
float tmp1 = Vector3.Distance(players[0].transform.position, bots[1].transform.position);
if (tmp1 < distance)
{
distance = tmp1;
botNearest = bots[1];
}
}
if (players[1] != null)
{
float tmp1 = Vector3.Distance(players[1].transform.position, bots[1].transform.position);
if (tmp1 < distance)
{
distance = tmp1;
botNearest = bots[1];
}
}
if (players[2] != null)
{
float tmp1 = Vector3.Distance(players[2].transform.position, bots[1].transform.position);
if (tmp1 < distance)
{
distance = tmp1;
botNearest = bots[1];
}
}
}
if (bots[2] != null)
{
if (players[0] != null)
{
float tmp1 = Vector3.Distance(players[0].transform.position, bots[2].transform.position);
if (tmp1 < distance)
{
distance = tmp1;
botNearest = bots[2];
}
}
if (players[1] != null)
{
float tmp1 = Vector3.Distance(players[1].transform.position, bots[2].transform.position);
if (tmp1 < distance)
{
distance = tmp1;
botNearest = bots[2];
}
}
if (players[2] != null)
{
float tmp1 = Vector3.Distance(players[2].transform.position, bots[2].transform.position);
if (tmp1 < distance)
{
distance = tmp1;
botNearest = bots[2];
}
}
}
Ответы (1 шт):
Автор решения: aepot
→ Ссылка
Здесь особо нечего мудрить, по сути это каждый с каждым
public Bot FindClosestBot(out float distance)
{
Bot closestBot = null;
distance = 0f;
foreach (var player in players)
{
foreach (var bot in bots)
{
if (player != null && bot != null)
{
float tmp = Vector3.Distance(player.transform.position, bot.transform.position);
if (tmp < distance || closestBot == null)
{
distance = tmp;
closestBot = bot;
}
}
}
}
return closestBot;
}
Пользоваться так
var bot = FindClosestBot(out float distance);
if (bot != null)
{
Debug.Log($"Ближайший бот {bot.Name} на дистанции {distance}");
}
else
{
Debug.Log("Бот не найден");
}