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
4 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.

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.

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

2 answers

Log in to vote
2
Answered by 4 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:

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)
Ad
Log in to vote
1
Answered by
Necro_las 412 Moderation Voter
4 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.

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)

Answer this question