Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I properly detect if two objects are intersecting or are within a radius of eachother?

Greetings! I'm working on a script that spawns portals in random locations, but they more often then not spawn very close together or intersecting. I tried to figure out whats going on but I can't quite figure out why.

local RetrievedTreasures = {}

local function CheckIntersection(Object, Treasures)
	local Intersects = false
	for _,v in pairs(Treasures) do
		local radius = 2.5
		if Object:GetPrimaryPartCFrame().p.Z < (v.WepPosZ + radius) 
			and Object:GetPrimaryPartCFrame().p.Z > (v.WepPosZ - radius) 
			and Object:GetPrimaryPartCFrame().p.Y < (v.WepPosY + radius) 
			and Object:GetPrimaryPartCFrame().p.Y > (v.WepPosY - radius) then 
			Intersects = true break 
		end
	end
	return Intersects
end

local function CreatePortal()
	local Intersect = true
	while Intersect do
		--summon portal function
		Intersect = CheckIntersection(Portal, RetrievedTreasures)
		wait()
	end
end
CreatePortal()

This function is supposed to sort through the values in table of logged portals and check if the new portal is within radius of an existing one. Putting a radius value of 4 or lower seems to work fine, but 5 or higher breaks it. The new portal just flashing over the place looking for a suitable spot.

Although my main problem is that that they will spawn intersecting or within radius.. Any ideas as to what I'm doing wrong here? Thanks in advance.

1 answer

✓ Accepted answer

Hello!

So there's a more efficient and trustworthy way to check the distance between two objects. You can just do:

local distance = (object1.Position - object2.Position).Magnitude
if distance < 25 then
	print("Less than 25 studs away")
end

Read this for more information on Magnitude.

I hope this helps you, as Magnitude is a solid-built in way to check the distance!

If this doesn't work or you have any questions feel free to ask them in the comments, or I could give you my Discord.

-ProqrammedGreen

2 comments

0

I will give this a try. Thanks

0

Works like a charm. Thanks you.

This discussion is preserved as it was. New answers, comments, and votes are closed.