如何统一找到数组中第二近的对象? [复制]
Posted
技术标签:
【中文标题】如何统一找到数组中第二近的对象? [复制]【英文标题】:How to find second closest object in array in unity? [duplicate] 【发布时间】:2022-01-16 06:12:03 【问题描述】:我在 Unity 中遇到问题。我想创建一个脚本,它能够找到离玩家最近的物体(我设法做到了)和离玩家第二近的物体。我的问题是如何修改此代码使其也适用于第二个对象?
public class Robot2 : MonoBehaviour
public GameObject cameraHolder;
public Transform[] objects;
private Transform nearestObj;
private Transform secondObj;
void Update()
float lowestDist = Mathf.Infinity;
nearestObj = null;
secondObj = null;
foreach(Transform obj in objects)
float dist = Vector3.Distance(transform.position, obj.position);
if(dist < lowestDist)
lowestDist = dist;
nearestObj = obj;
Debug.DrawLine(transform.position, nearestObj.transform.position, Color.red);
cameraHolder.transform.position = nearestObj.transform.position;
【问题讨论】:
【参考方案1】:您可以像下面的代码一样使用 LINQ:
Objects.ToList().OrderBy(o => Vector3.Distance(transform.position, o.position))[1]
或
Objects.ToList().OrderByDescending(o => Vector3.Distance(transform.position, o.position))[1]
【讨论】:
【参考方案2】:你可以这样做:
float lowestDistance = Mathf.Infinity;
float nextLowestDistance = Mathf.Infinity;
nearestObject = null;
secondObject = null;
foreach ( Transform object in objects )
float dist = Vector3.Distance( object.position, transform.position );
if ( dist < lowestDistance )
if ( lowestDistance < nextLowestDistance )
nextLowestDistance = lowestDistance;
secondObject = nearestObject;
lowestDistance = dist;
nearestObject = object;
else if ( dist < nextLowestDistance )
nextLowestDistance = dist;
secondObject = object;
【讨论】:
以上是关于如何统一找到数组中第二近的对象? [复制]的主要内容,如果未能解决你的问题,请参考以下文章