Distance between entities

Hello, i’m having some problems with finding distance between entities, i’m a real lua noobie.
Let’s say I have a couch and a table and I want to check if they are close enough, it’ll print a message “The couch and the table are close( less then 100 units )”
I found this code online, but im not sure how I can get it to work…


function DistanceInformation(entity)
	for k,v in pairs(ents.GetAll()) do
		if v:GetClass() == "couch" && v:GetPos():Distance(entity:GetPos()) < 100 then
			print("its less than 100 units away")
		else
			print("its more than 100 units away")
		end
	end
end	

I put the code into one of the entities init.lua file and called a timer on it(I need to check if both entities are close to each other every 1 sec).
And my console just get spammed by “its more than 100 units away” (not by the timer), and then this error comes up:
Attempt to call method GetPos (a nil value), I understand there’s a problem, I cant find it though :\

Hey zarko. I worked out a basic example for you, although I’m not sure if it works, I haven’t worked with lua in a little while. I’ll check it out.




-- Spawn a prop and run this code near it.

local ply = LocalPlayer() -- define ply as YOU.

for k,v in pairs ( ents.GetAll() ) do -- check every entity or prop on the map.

	if v:GetClass() == "prop_physics" then -- make sure it's a prop_physics class.

		if ply:GetPos():Distance( v:GetPos() ) <= 100 then -- also check if it's within 100 units.

			print( ply:GetPos():Distance( v:GetPos() ) ) -- If so, print the distance of that.

		end
	end
end


Thanks for the help, but this isnt what I am looking for.
I have 2 entities that you can buy from the DarkRP f4 menu, and when someone buys them, I need to check on one of them if he is close to the other, if he is, continue with a timer, if its not close, pause a timer.

EDIT:
Thank you, but still, should I just change the ply to ENT?

Edit 2:
Does not work :\ , tried to do it first as a player, then if it work play with it.
It gives me attempt to call global LocalPlayer (a nil value) :\ .

This should work for your init.lua file. Although, it’s more difficult to explain how you can create and destroy your timer with this hook.




function ENT:Think() -- Check every 1/16th of a second

	for k,v in pairs ( player.GetAll() ) do -- run through every player in map.

		if self:GetPos():Distance( v:GetPos() ) <= 100 then -- check if it's within 100 units.

			print( ply:GetPos():Distance( v:GetPos() ) ) -- If so, print the distance of that.

		end

	end

end



Got it to work :slight_smile:
Thank you very much !

Great!
By the way, welcome to Facepunch.