EgonMilanVotrubec

ClosestObject Brute Force

Nov 19th, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.38 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class Closest : MonoBehaviour
  4. {
  5.     [Tooltip ( "The array of objects to check." )]
  6.     public Transform [ ] PArray;
  7.  
  8.     public Transform ClosestP { get; private set; } = null;
  9.  
  10.     [Tooltip("A default of '1' indicates that we check once a second for the closest object.")]
  11.     public float CheckInterval = 1;
  12.     private float timer = 0;
  13.  
  14.     private void Start ( )
  15.     {
  16.         // Make sure that we calculate the distance once at the very beginning.
  17.         timer = CheckInterval + float.Epsilon;
  18.     }
  19.  
  20.     void Update()
  21.     {
  22.         timer += Time.deltaTime;
  23.         if ( timer >= CheckInterval )
  24.         {
  25.             timer -= CheckInterval;
  26.  
  27.             var closestPIndex = ClosestPIndex ( );
  28.  
  29.             if ( closestPIndex >= 0 )
  30.                 ClosestP = PArray [ closestPIndex ];
  31.  
  32.             // ClosestP is now your closest object.
  33.         }
  34.     }
  35.  
  36.     private int ClosestPIndex ( )
  37.     {
  38.         var closestIndex = -1;
  39.         var closestDistance = float.MaxValue;
  40.         for ( int i = 0; i < PArray.Length; i++ )
  41.         {
  42.             var sqrMagnitude = ( transform.position - PArray [ i ].position ).sqrMagnitude;
  43.             if ( sqrMagnitude < closestDistance )
  44.             {
  45.                 closestDistance = sqrMagnitude;
  46.                 closestIndex = i;
  47.             }
  48.         }
  49.         return closestIndex;
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment