GE Lua Documentation

Press F to search!

getNearestTrafficVehicle

Definition


-- @/lua/ge/extensions/gameplay/traffic/trafficUtils.lua:611

local function getNearestTrafficVehicle(pos, filters) -- returns the nearest traffic vehicle to the given position
  filters = filters or {}
  pos = pos or core_camera.getPosition()

  local bestId
  local bestDist = math.huge
  for _, id in ipairs(gameplay_traffic.getTrafficAiVehIds()) do
    local veh = gameplay_traffic.getTraffic()[id]
    local valid = true
    for k, v in pairs(filters) do -- optional filters by traffic vehicle properties
      if veh[k] ~= nil and veh[k] ~= v then
        valid = false
        break
      end
    end

    if valid then
      local otherPos = veh.pos
      local dist = pos:squaredDistance(otherPos)
      if dist < bestDist then
        bestId = id
        bestDist = dist
      end
    end
  end

  return bestId, math.sqrt(bestDist)
end

Callers