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.
1 | local part = script.Parent |
2 |
3 | -- Parts position is -223.845, 21.141, -0.373 |
4 |
5 | local 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.
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:
01 | game.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 ) |
11 | 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.
1 | local part = script.Parent |
2 | local TriggerArea = script.Parent.TriggerArea -- as you create one like this |
3 |
4 | TriggerArea.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 |
9 | end ) |