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

How to detect distance?

How do you make it so that a brick or model can tell when a part is near them (say, 50 studs away). I'm really stumped by this problem, although I suspect it has something to do with using the Magnitude between bricks.

I'm creating a script so that when a part is x far away, a stuff happens.

2 answers

✓ Accepted answer

Yes, you would use Magnitude to get the distance between two parts. I provided a script to help you out.

For a player: This would be a local script in Workspace. This will work for each individual player.

torso = game.Players.LocalPlayer.Character.Torso
part2 = game.Workspace.Part2

if (torso.Position - part2.Position).magnitude >= 40) then
	print('It is 40 studs away!!!')
end

10 comments

0

But if I don't know what Part1 is (such as any player on the server), how do I make it print that when any player gets >= 40 studs away.

0

This would be a local script and the part1 path (Could change the variable) could lead to the player's torso (game.Players.LocalPlayer.Character.Torso).

0

Yes, but what if I don't know the Player is what I'm saying. I want it to be any of the 20 players on the server so I can't just make a path to a defined part.

0

For the Player's torso, you can. I'll update the script with an example.

0

Ohhhhh. Using LocalPlayer! I get it now! thanks!

0

Actually, it turns out it doesn't work.

0

Do you get any errors? I used this same way earlier with another script and it worked like a charm.

0

Try putting it in StarterGui.

0

Putting it in the StarterGui causes Studio to crash...

0

Did you Publish it and test it by pressing 'Play'?

For detecting the distance between an object and another object, preferably, I would use magnitude. This is a very good example of magnitude provided by ScriptOn

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