我正在嘗試撰寫一個最近鄰演算法,但我不確定它為什么不起作用,立方體是由物件池系統產生的,它應該考慮到它周圍具有相同腳本的其他立方體附上,這是我當前的腳本:
public class FindNearestNeighbour : Closest, IPooledObject
{
public static List<FindNearestNeighbour> findNearestNeighbours = new List<FindNearestNeighbour>();
private void Start()
{
findNearestNeighbours.Add(this);
}
void FindClosestObject(Vector3 from, List<FindNearestNeighbour> transforms)
{
if (transforms.Count > 1)
{
Vector3 location = Vector3.zero;
float Closest = Mathf.Infinity;
for (int i = 0; i < transforms.Count; i )
{
Vector3 loc = transforms[i].transform.position;
if (from != loc)
{
float distance = Mathf.Abs(loc.sqrMagnitude - from.sqrMagnitude);
if (distance < Closest)
{
Closest = distance;
location = loc;
Debug.DrawLine(from, location, Color.red);
}
}
}
}
}
public void OnObjectSpawn()
{
FindClosestObject(transform.position, findNearestNeighbours);
}
}

uj5u.com熱心網友回復:
我認為你的第一個主要問題是你一直打電話
Debug.DrawLine(from, location, Color.red);
當您仍在回圈中并且可能還有更近的鄰居尚未找到時。
整個回圈結束后,您只需要一次呼叫!
然后你做的第二個
float distance = Mathf.Abs(loc.sqrMagnitude - from.sqrMagnitude);
這沒有任何意義!這將計算兩個位置與(世界原點)的個人距離Vector3.zero的差異,而不是這兩者之間的差異!
你想要的是
float distance = (loc - from).sqrMagnitude;
正如rustyBucketBay已經提到的
使用Linq您可以在一行中執行此操作:
using System.Linq;
...
// First filter out null items and yourself!
FindNearestNeighbour closest = findNearestNeighbours.Where(n => n && n != this)
// Then order by the distance where sqrMagnitude is significantly more
// efficient than using Vector3.Distance or magnitude
.OrderBy(n => (n.transform.position - transform.position).sqrMagnitude)
// finally return the first (closest) or null if there wasn't any
.FirstOrDefault();
為什么這么強大?
因為您可以輕松調整它并執行例如
// First filter out null items and yourself!
FindNearestNeighbour[] closest = findNearestNeighbours.Where(n => n && n != this)
// Then order by the distance where sqrMagnitude is significantly more
// efficient than using Vector3.Distance or magnitude
.OrderBy(n => (n.transform.position - transform.position).sqrMagnitude)
// finally return up to the first ten (closest) items
.Take(10).ToArray();
找到最接近的 X 專案,而不必讓你的回圈變得超級復雜。
看
- 林克
Where - 林克
OrderBy - 林克
FirstOrDefault - 林克
Take
uj5u.com熱心網友回復:
您正在減去以下位置的平方:
float distance = Mathf.Abs(loc.sqrMagnitude - from.sqrMagnitude);
我認為你最好這樣做:
float distance = (loc - from).sqrMagnitude;
這是距離的平方大小。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424318.html
