ents.FindByClass("npc_")
or
ents.FindInRadius()
loop and check if IsNPC()
Which do you think is least demanding on the CPU?
Depends on what you're doing after you loop.
Well I need to check the distance of each found npc with a point and find the closest npc
This :
[lua]
local function findNearest( t_ent )
local lDist = nil;
local r_ent = nil;
for _, ent in pairs( ents.FindByClass( "npc_*" ) ) do
if ( !lDist || t_ent:GetPos():Distance( ent:GetPos() ) < lDist ) then
lDist = t_ent:GetPos():Distance( ent:GetPos() );
r_ent = ent;
end
end
return r_ent;
end
[/lua]
Now would I be able to get away with throwing a util.QuickTrace() in there for a line of sight test? Or does someone have a better idea?
[QUOTE=>>oubliette<<;39938661]This :
[lua]
local function findNearest( t_ent )
local lDist = nil;
local r_ent = nil;
for _, ent in pairs( ents.FindByClass( "npc_*" ) ) do
if ( !lDist || t_ent:GetPos():Distance( ent:GetPos() ) < lDist ) then
lDist = t_ent:GetPos():Distance( ent:GetPos() );
r_ent = ent;
end
end
return r_ent;
end
[/lua][/QUOTE]
This is not the most efficient. The Distance function performs an unnecessary square root - you should use LengthSqr instead:
[lua]local function findNearest(point)
local mindist = math.huge
local ent
for _, e in ipairs(ents.FindByClass( "npc_*" )) do
local dist = (point - e:GetPos()):LengthSqr()
if dist < mindist then
mindist = dist
ent = e
end
end
return ent
end[/lua]
[QUOTE=>>oubliette<<;39943656]It's not unnecessary, dist = sqrt( ( x1^2 - x2^2 ) + ( y1^2 - y2^2 ) + ( z1^2 - z2^2 ) )[/QUOTE]
It is unnecessary. If you don't need to know the actual distance to the nearest NPC, you can find which one is closest by comparing the squared distances thus removing calls to square root.
[editline]17th March 2013[/editline]
LengthSqr = x[sup]2[/sup] + y[sup]2[/sup] + z[sup]2[/sup]
[QUOTE=>>oubliette<<;39943656]It's not unnecessary, dist = sqrt( ( x1^2 - x2^2 ) + ( y1^2 - y2^2 ) + ( z1^2 - z2^2 ) )[/QUOTE]
[IMG]http://i.imgur.com/XfcGzyG.png[/IMG]
Why perform an extra square root on each "distance" if you can just compare c^2.
[QUOTE=MakeR;39943710]It is unnecessary. If you don't need to know the actual distance to the nearest NPC, you can find which one is closest by comparing the squared distances thus removing calls to square root.
[editline]17th March 2013[/editline]
LengthSqr = x[sup]2[/sup] + y[sup]2[/sup] + z[sup]2[/sup][/QUOTE]
Okay, fair enough.
[QUOTE=kklouzal23;39938766]Now would I be able to get away with throwing a util.QuickTrace() in there for a line of sight test? Or does someone have a better idea?[/QUOTE]
If you're trying to make an aimbot, this isn't the way to do it.
If you're not, what are you trying to do?
Sorry, you need to Log In to post a reply to this thread.