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

Best way to detect when something is in range?

Say you have a huge game, and you're trying to make it so if you're close to a part, you can press any key and interact with it. What would be the fastest, and most efficient way to do this?

I've heard people talk about using FindPartOnRay and FindPartsInRegion3, and then there are still people who just collect every part in their game in a table and decide what is closest to what (which I really want to avoid doing).

Most efficient updater

The biggest part to this question, is what method I should use to do this. Should I update my code with a loop to check constantly if a part is in range, or can I use an event instead? I'd like to use an event, just to avoid unnecessary script performance.

So anyway, if someone share their thoughts on this, I'd really appreciate it. Just basically wondering what I can use to see if a part is in range, and what to use to check when it is (via loops or events).

1 comment

0

Have you tried using magnitudes? You can check if a player is within range of an object and execute code if they're within the area

1 answer

✓ Accepted answer

Check the distance
Magnitude

Assuming you're worried about a specific part, you're pretty clear to just check in a loop.

-- Assumes predeclared Part and Torso
while wait(0.08) do
	if (Part.Position - Torso.Position).magnitude < 20 then -- Within 20 studs?
		-- Allow interaction
	else
		-- Deny interaction (If you need to do something)
	end;
end;

However, because you're doing it for a key press you may want to only check when you press the key unless you need interaction cues.

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