How do I make a script wait for a part to get to a certain position?

I want to make a script wait for a part to get to a certain position, like how humanoids have a MoveToFinished event. Instead of experimenting for an hour and calling myself stupid when I figure it out, I want to see if anybody else knows. Currently, my script just makes the part try going to different places a hundred times a second.

Here it is:

local Hum = script.Parent.Parent.Humanoid
local Root = script.Parent
local Force = script.Parent.BodyForce
local Speed = 3000
Hum.Swimming:Connect(function()
Hum.AutoRotate = false
Speed = 3000
end)
Hum.Running:Connect(function()
Hum.AutoRotate = true
Force.Force = Vector3.new(0,0,0)
Speed = 0
end)
while true do
local Destination = Vector3.new(Root.Position.X + math.random(-50,50),Root.Position.Y + math.random(-50,50),Root.Position.Z + math.random(-50,50))
Root.CFrame = CFrame.lookAt(Root.Position,Destination)
Force.Force = Root.CFrame.LookVector*Speed
wait(0.01)
end

It’s pretty unlikely that a part will ever reach an exact desired position when moving it with the physics engine. A common approach is to see if it’s within a certain distance of the target position. Here’s how you can break out of the loop when the part is “close enough”:

local closeEnoughDistance = 1 --How close two points must be to be considered "close enough to equal"
repeat
    local Destination = Vector3.new(Root.Position.X + math.random(-50,50),Root.Position.Y + math.random(-50,50),Root.Position.Z + math.random(-50,50))
    Root.CFrame = CFrame.lookAt(Root.Position,Destination)
    Force.Force = Root.CFrame.LookVector*Speed
    
    local closeEnough = (Destination - Root.Position).Magnitude <= closeEnoughDistance
    
    --Not strictly necessary, but does prevent the loop from looping one too many times.
    --    That could lead to wasting 1/30th of a second, or worse overshooting if the part is moving real fast
    if not closeEnough then
        wait(0.0333) --`wait` cannot actually wait for less than 1/30th of a second, AFAIK
    end
until closeEnough
1 Like