Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to see if player walked near a part?

Asked by
14dark14 167
5 years ago

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.

1local part = script.Parent
2 
3-- Parts position is  -223.845, 21.141, -0.373
4 
5local humanoid -- Get the humanoid of the player or something
6    if humanoid ~= nil then
7        print("Someone walked near me")
8    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.

0
Sometimes, you have to go on with not too professional things, if it is possible to make it easier. DangerousKillerTimur 54 — 5y

2 answers

Log in to vote
2
Answered by 5 years ago

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:

01game.Players.PlayerAdded:Connect(function(player) -- This gives us a player object to use
02    player.CharacterAdded:Connect(function(char) -- This gives us the character object of the player
03        local part = script.Parent
04        while true do
05            wait()
06            if (part.Position - char.HumanoidRootPart.Position).Magnitude <= 10 then -- If the player is within 10 studs of the part...
07                -- Do something here
08            end
09        end
10    end)
11end)
Ad
Log in to vote
1
Answered by
Necro_las 412 Moderation Voter
5 years ago

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.

1local part = script.Parent
2local TriggerArea = script.Parent.TriggerArea -- as you create one like this
3 
4TriggerArea.Touched:Connect(function(hit)
5    if hit.Parent.Humanoid then
6        local player = game.Players:GetPlayerFromCharacter(hit.Parent)
7        print("Player near part: " .. player)
8    end
9end)

Answer this question