# loop question

## Recommended Posts

I want to check which ped is the closest to the wx,wy,wz position. Is there any easier way do it then this method?

local wx = 0
local wy = 0
local wz = 0

function test()
for i,v in ipairs(getElementsByType("ped")) do
local x,y,z = getElementPosition(v)
local distance = getDistanceBetweenPoints3D(x,y,z,wx,wy,wz)
for i,v2 in ipairs(getElementsByType("ped")) do
local x,y,z = getElementPosition(v)
local distance2 = getDistanceBetweenPoints3D(x,y,z,wx,wy,wz)

if distance < distance2 then
---
end
end
end
function getDistanceBetweenElements(arg1, arg2)
local element1 = Vector3(getElementPosition( arg1 ))
local element2 = Vector3(getElementPosition( arg2 ))
local distance = getDistanceBetweenPoints3D( element1,element2 )
return distance
end

That's not exactly what i need. I want to loop throught all peds and get the one that is the closest to a given position. Its not that difficult, i just wanna know if theres any simpler way to do it, so i dont have to loop twice

try it

local wx , wy , wz  = 0 , 0 , 0

function test(  )
local peds , positions , ped = getElementsByType( "ped" ) , { } , { };
for index = 1 , #peds do
local distance = getDistanceBetween3DPoints( wx , wy , wz , getElementPosition( peds[ index ] ) );
table.insert( positions , distance ) ; ped[ distance ] = peds[ index ]
end
return ped[ math.min( unpack( positions ) ) ];
end

• 1

## Create an account

Register a new account