我在团结中挣扎。我想创建一个脚本,能够找到离玩家最近的对象(我设法做到了),以及离玩家第二近的对象。我的问题是如何修改此代码,使其也适用于第二个对象?
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;
}
}
你可以像下面的代码一样使用LINQ:
Objects.ToList().OrderBy(o => Vector3.Distance(transform.position, o.position))[1]
或者
Objects.ToList().OrderByDescending(o => Vector3.Distance(transform.position, o.position))[1]
您可以这样做:
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;
}
}