Find the nearest location on given vector array on Unreal Engine

Jeewantha Lahiru
2 min readApr 20, 2024

When you are using Unreal Engine, sometimes you may need to find the nearest location for a certain location using a vector array. For example, if you have a line trace and there are multiple actors each having several locations stored in an array, you need to find the closest location to the impact location within your vector array. (I’m doing this using blueprints)

so you have to do like this,

  • Create a function and name it as you need. I suggest naming it “GetNearestLocation” with a vector input called “HitPoint”. This input specifies the point from which you want to find the nearest location within the given array.
  • Then, obtain the array length. If the length is greater than 1, you can proceed with the calculation. Otherwise, you can simply return the value at the 0th index.
  • Create a forEach loop for the given array. If the index equals 0, then instantiate a variable called “ClosestIndex” and set its value to 0. Next, calculate the distance from the hit location to the value at the 0th index and assign this distance to a variable named “ClosestDistance”. Ensure that these variables are declared locally.
  • If the index is not equal to 0, then verify whether the calculated distance is less than the ClosestDistance. If this condition holds true, update the ClosestDistance with the calculated distance and set the ClosestIndex to the current ArrayIndex.
  • Then you can return the closest value by getting the value of the given array’s ClosestIndex.
  • I will add a full code image down below

--

--

Jeewantha Lahiru

Undergraduate Software Engineer in University of Kelaniya