so this script is to control units movement. to control the unit you click anywhere on the map and the unit move there. the unit is kinda slow so it might stop midway and i know that if the mousepos too far and the unit didnt reach it in 8 seconds it will stop so how to make when the units stop in midway it keep moveto without using too much moveto
game.ReplicatedStorage.Events.UnitControl.OnServerEvent:Connect(function(plr, mousepos, selected)
player = plr
if selected then
if selected:FindFirstChild("Moving") and selected:FindFirstChild("Humanoid") then
if selected:FindFirstChild("Moving") then
selected.Moving.Value = true
end
selected.Humanoid:MoveTo(mousepos)
selected.Humanoid.MoveToFinished:Wait()
if selected:FindFirstChild("Moving") then
selected.Moving.Value = false
end
game.ReplicatedStorage.Events.UnitReaches:FireClient(plr)
end
end
end)
You can use a loop to keep checking if the unit has reached the mouse position or if it has stopped midway. If it has stopped midway, you can call the MoveTo() function again with a new destination, which is closer to the mouse position. You can also use a time limit to stop the loop if the unit has not reached the mouse position within a certain time. So like:
game.ReplicatedStorage.Events.UnitControl.OnServerEvent:Connect(function(plr, mousepos, selected)
player = plr
if selected then
if selected:FindFirstChild("Moving") and selected:FindFirstChild("Humanoid") then
if selected:FindFirstChild("Moving") then
selected.Moving.Value = true
end
local humanoid = selected.Humanoid
local currentPos = humanoid.RootPart.Position
local direction = (mousepos - currentPos).Unit
local distance = (mousepos - currentPos).Magnitude
local maxTime = 8 -- in seconds
local startTime = tick()
while distance > 0.5 and tick() - startTime < maxTime do
humanoid:MoveTo(currentPos + direction * math.min(distance, 10))
humanoid.MoveToFinished:Wait()
currentPos = humanoid.RootPart.Position
distance = (mousepos - currentPos).Magnitude
end
if selected:FindFirstChild("Moving") then
selected.Moving.Value = false
end
game.ReplicatedStorage.Events.UnitReaches:FireClient(plr)
end
end
end)
This code checks if the unit has reached the mouse position by calculating the distance between the current position and the mouse position. If the distance is less than a certain threshold (0.5 in this case), the loop stops. If the unit has not reached the mouse position within 8 seconds, the loop also stops. The MoveTo() function is called with a new destination, which is the current position plus the direction towards the mouse position times the minimum between the remaining distance and a fixed distance (10 in this case). This ensures that the unit moves towards the mouse position but not too far away, which could cause it to stop midway again.
it doesnt work it still stops after 8 second not reaching the mouse position maybe make a line of code which checks if the units position is not in mouse position it calles the move to?