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

How to see if player walked near a part?

I have NPC in a game and I want to make it so if you walk near the NPC text will appear on your screen. I know I could just add an invisible part that the player would step on, but that is not very professional.

local part = script.Parent

-- Parts position is  -223.845, 21.141, -0.373

local humanoid -- Get the humanoid of the player or something
	if humanoid ~= nil then
		print("Someone walked near me")
	end

The player walks near the part ( like 5 - 10 studs ) and the function will run. It would be great if you included how to get player from the character in the answer.

1 comment

0

Sometimes, you have to go on with not too professional things, if it is possible to make it easier.

2 answers

✓ Accepted answer

Magnitude is what you should use here.

The magnitude of a vector is the vector's length. The magnitude of two vectors is the distance between those two vectors.

So, here is an example of using it in your case:

game.Players.PlayerAdded:Connect(function(player) -- This gives us a player object to use
	player.CharacterAdded:Connect(function(char) -- This gives us the character object of the player
		local part = script.Parent
		while true do
			wait()
			if (part.Position - char.HumanoidRootPart.Position).Magnitude <= 10 then -- If the player is within 10 studs of the part...
				-- Do something here
			end
		end
	end)
end)

I don't know if is the best solution, but in these cases I use Touched event in an invisible part welded to the the main part to create an area of trigger.

local part = script.Parent
local TriggerArea = script.Parent.TriggerArea -- as you create one like this

TriggerArea.Touched:Connect(function(hit)
	if hit.Parent.Humanoid then
		local player = game.Players:GetPlayerFromCharacter(hit.Parent)
		print("Player near part: " .. player)
	end
end)

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