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

How to determine a wait time based on the magnitude of 2 positions?

Asked by 4 years ago

Hi peoples. I am creating an NPC follow script and as you may know, if you add a while true do loop and just a wait() to it, it will be very laggy because of how many requests it gets. To solve this, all you need to do is add value to the wait. Now, if the player is far enough away from the NPC can you call the function every 2 seconds then the same thing will happen. That's why I thought of getting the distance of the NPC's humanoid root part and the distance of the character's humanoid root part and determining a waiting time based on that information. Except for all the times I have tried to do this, it has failed. Horribly. Usually returning a value of between 100 and 300. So I could really use some help on this one. Thanks <3

Here is a little example of what I've tried to do.

local npcRoot = npc.HumanoidRootPart
local playerRoot = player.HumanoidRootPart

local waitTime = (npcRoot.Position - playerRoot.Position).Magnitude

print(waitTime)

Again, I have no idea what I'm doing. I've used the Magnitude function before but never like this. Any help would be appreciated <3

1 answer

Log in to vote
0
Answered by
starmaq 1290 Moderation Voter
4 years ago

The idea you have is indeed right, but it has a missing component, you can use the formula of finding time, distance and speed in order to find the time you need to wait. I shouldn't even explain this is so easy. This image might even explain everything

The distance will be the magntiude, the speed will actually be the WalkSpeed of the NPC or player. And yeah, magnitude/WalkSpeed should give us the time we need to wait! (

Things don't actually work this way, but this is an approxamation, since really when we devide the distance by the speed, we are getting the time we need to walk from point A to point B with a certain distance between them and a certain speed we have, but here we are trying to find the time that we need to wait each time a loop loops which is differnet. But hay I assume it'll work.

So

local npcRoot = npc.HumanoidRootPart
local npcSpeed = npc.Humanoid.WalkSpeed
local playerRoot = player.HumanoidRootPart

local waitTime = (npcRoot.Position - playerRoot.Position).Magnitude / npcSpeed

print(waitTime)

Yeah, this should be good, if the distance was 100, and the walkspeed which will always be 16 (the default walkspeed when a humanoid is instanced), we get a waitTime of 6.15, which is great!

But if you wanted to ignore all this, you can simply divide the magnitude by any number really to make the waitime always relevant to the distance but we reduce it to make it short.

local npcRoot = npc.HumanoidRootPart
local playerRoot = player.HumanoidRootPart

local waitTime = (npcRoot.Position - playerRoot.Position).Magnitude / 100  
-- 100 is an example

print(waitTime)
Ad

Answer this question