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 detect if a player comes NEAR something without touching?

2 answers

✓ Accepted answer

First off, you gotta know how magnitude works.

Magnitude

Magnitude is the length of a vector. If you get the magnitude of a vector, you are receiving the length of that vector, in studs.

local vec = Vector3.new(0,5,5) --Define a vector
print(vec.magnitude) --Print out the magnitude
--> 7.071067810058 --Receive the length

Now, if you subtract two vectors from eachother, it creates a vector that is the length of the distance between them. Get the magnitude of that vector and you receive a number, approximately how far away the two vectors are from eachother.

local v1 = Vector3.new(0,0,-5) --First vector
local v2 = Vector3.new(0,5,5) --Second vector
local dist = v2 - v1  --Create another vector, of the difference between the two
print(dist.magnitude); --Now get the distance of it, using magnitude.
--> 11.180339813232

Applying to your code

In a script inside the player's Character, use magnitude to check the distance from the torso to the object. If the number you get back is lower than your desired distance, then the player is near your object.

local part = workspace.Part --Define your part!!
local tor = script.Parent --This is the torso
local near = 5 --The distance, in studs, how far 'near' is.

while wait(1) do
	--Get the distance
	local dist = (tor.Position - part.Position).magnitude
	--Check if it's near
	if dist <= near then
		--If so, announce it in the output.
		print(tor.Parent.Name.." is near "..part.Name.." !"
	end
end

1 comment

1

Why don't you use the :DistanceFromPlayer(part.Position) method?

local door = script.Parent

while true do
	for i,v in pairs(game.Players:GetChildren()) do
		if (v.Character.Torso.Position - door.Position).magnitude <= 20 then
			door.Transparency = (v.Character.Torso.Position - door.Position).magnitude/15
		else
			door.Transparency = 1
		end
	end
	wait()
end

heres an other example it will make the door get more and more visible when the players torso get closer to it and will fade out when the player walks further away

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