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

Efficiency in checking for position / magnitude?

Asked by
LuaQuest 450 Moderation Voter
9 years ago

So I'm trying to make a basic NPC-like dialog GUI appear when a player walks near a certain part. Only problem is, I feel as if my code is somewhat inefficient. I use a while loop and magnitude to compare the player's torso position, to the target part. Here's a brief example of what it looks like:

01-- Services
02local players = game:GetService("Players")
03 
04-- Client
05local client = players.LocalPlayer
06local mouse = client:GetMouse()
07local char = client.Character or client.CharacterAdded:wait()
08local torso = char:WaitForChild("Torso")
09 
10-- Workspace
11local npc = workspace:WaitForChild("NpcPart")
12 
13-- Main loop
14while wait(1) do
15    if (torso.Position  - npc.Position).Magnitude < 10 then
16        print("Player is in range")
17    end
18end

So this does work, however If i wanted a really vast amount of NPC objects, I feel like this could get messy and inefficient really quick. I've also heard about Region3, but I'm not sure if that would be a good choice either.

If someone knows a bit more about this than me and is willing to share, I'd appreciate it!

1 answer

Log in to vote
0
Answered by
Fubl 15
9 years ago

Roblox's Dialog has a property called ConversationDistance which disables the Dialog until the Player's Character is within range. That's the baked-in solution.

If you are using a custom implementation of NPC dialogue, just check the magnitude whenever a Player attempts to initiate the dialogue (i.e clicks on the npc or shoots at it or something)

Ad

Answer this question