• Closet entity from a table of entities?
    5 replies, posted
What is the most efficient way to find the closest entity to a player, from a table of entities?
[lua]local plypos = ply:GetPos() local dist, ent = math.huge for _, v in ipairs( table_of_ents ) do local vdist = (v:GetPos() - plypos):LengthSqr() if vdist < dist then dist = vdist ent = v end end[/lua] Obviously, replace ply with the player and table_of_ents with your table of entities.
[QUOTE=Dreken;41794450]What is the most efficient way to find the closest entity to a player, from a table of entities?[/QUOTE] If exact units doesn't matter and you just want to know which has the smallest value, you can use LengthSqr() [lua](dest - currentpos):LengthSqr()[/lua] You would use LengthSqr in this situation because it's cheaper than Distance, but still gives a value that's relative to distance.
Why does distance do things in a more slow manner? Is it just that perhaps Distance() is handled in lua, and LengthSqr() in C++? If not, why not just override Distance()? [lua] local vec = FindMetaTable("Vector") function vec:Distance(vect) return (vect-self):LengthSqr() end [/lua]
[QUOTE=Bletotum;41794835]Why does distance do things in a more slow manner? Is it just that perhaps Distance() is handled in lua, and LengthSqr() in C++? If not, why not just override Distance()? [lua] local vec = FindMetaTable("Vector") function vec:Distance(vect) return (vect-self):LengthSqr() end [/lua][/QUOTE] Because distance uses sqaure root to get the real, euclidean, distance. But square root is expensive.
[QUOTE=Bletotum;41794835]If not, why not just override Distance()? [lua] local vec = FindMetaTable("Vector") function vec:Distance(vect) return (vect-self):LengthSqr() end [/lua][/QUOTE] This wouldn't return the same value. LengthSqr returns the square of the distance.
Sorry, you need to Log In to post a reply to this thread.