Calculating path on a map

Hi, I am creating a function to calculate the amount of time it takes for a player to get from A to B, It will then wait for that amount of time, and will then update the players position in a table.

If the function is called a second time it should stop waiting for any current paths, calculate the position it got to between A and B, update the player position in the table, and then start a new calculation on the new A - B position.

The current script I have:

    function module:CalculatePath(Player, GoalPosition)
    	if not Player or not GoalPosition then return end
    	local CurrentTime = 0
    	if CurrentPath == false then
    		CurrentPath = true
    		local CurrentPosition = PlayerPositions[Player]
    		local Distance = (CurrentPosition - GoalPosition).Magnitude
    		local Direction = (GoalPosition - CurrentPosition).Unit
    		CurrentTime = Distance
    		while wait(0.1) and CurrentTime > 0 and CurrentPath == true do
    			CurrentTime = CurrentTime - 0.1
    		end

    		PlayerPositions[Player] = CurrentPosition + (Direction * Distance)
    	else
    		CurrentPath = false
    		print(PlayerPositions[Player])
    		return module:CalculatePath(Player, GoalPosition)
    	end
    end

This doesn’t work. Any help would be appreciated.

I find it vague to understand the goal behind your code. This is how I would calculate the travel time from the characters position to a given point:

local function getTravelTime(character, point)
	local rootPart = character:FindFirstChild("HumanoidRootPart")
	local humanoid = character:FindFirstChild("Humanoid")
	if rootPart and humanoid then
		-- delta time = distance / velocity
		return (rootPart.Position - point).Magnitude / humanoid.WalkSpeed
	end
end

This explains it a bit better I think.
image

https://developer.roblox.com/en-us/api-reference/event/Humanoid/MoveToFinished

All I want to happen, Is for when the function is called a second time it will end and restart the whole function.

local running = false
function module:CalculatePath(Player, GoalPosition)
	if not Player or not GoalPosition then return end
	local CurrentTime = 0
	running = false
	if CurrentPath == false then
		CurrentPath = true
		local CurrentPosition = PlayerPositions[Player]
		local Distance = (CurrentPosition - GoalPosition).Magnitude
		local Direction = (GoalPosition - CurrentPosition).Unit
		CurrentTime = Distance
		wait(0.1)
		running = true
		repeat
			CurrentTime = CurrentTime - 0.1
			wait(0.1)
		until running == false or CurrentTime <= 0 or CurrentPath == false

		PlayerPositions[Player] = CurrentPosition + (Direction * Distance)
	else
		CurrentPath = false
		print(PlayerPositions[Player])
		return module:CalculatePath(Player, GoalPosition)
	end
end

I have added a running variable to identify when the loop should finish if the function is run a second time.

1 Like