Ai didn't change waypoint after teleportation

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!

    I want Monster to change Waypoint after teleport.

  2. What is the issue? Include screenshots / videos if possible!

    after combine a teleport script with Ai script, it not working or result in Monster didn’t move.
    At first I try to separate a script into 2 script(Teleport Script and Ai Script) both of it working, but the result is Monster didn’t change waypoint after teleportation(because their in separate script).

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I did try to switch line of code, developer hub and devforum.

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

local PathfindingService = game:GetService("PathfindingService")
local Runservice = game:GetService("RunService")
local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local hrp = npc:WaitForChild("HumanoidRootPart")
local stuck = false
hrp:SetNetworkOwner(nil)



local walkAnim = humanoid.Animator:LoadAnimation(script.Walk)
local attackAnim = humanoid.Animator:LoadAnimation(script.Attack)
local RunAnim = humanoid.Animator:LoadAnimation(script.Run)

local pathParams = {
	AgentHeight = 9,
	AgentRadius = ((hrp.Size.X > 0 and hrp.Size.X) or hrp.Size.Y),
	AgentCanJump =((true ~= true) or false),
}

local rayParams = RaycastParams.new()
rayParams.FilterType = Enum.RaycastFilterType.Exclude
rayParams.FilterDescendantsInstances = {npc}

local lastPos
local animPlaying = false

local RANGE = script:WaitForChild("Range").Value
local Speed = script:WaitForChild("Runner").Value  --40
local NorSpeed = script:WaitForChild("Walker").Value --5

local function canSeeTarget(target)
	local orgin = hrp.Position
	local direction = (target.HumanoidRootPart.Position - hrp.Position).Unit * RANGE
	local ray = workspace:Raycast(orgin, direction, rayParams)

	if ray and ray.Instance then
		if ray.Instance:IsDescendantOf(target) then
			return true
		else
			return false
		end
	else
		return false
	end
end

local function findTarget()
	local players = game.Players:GetPlayers()
	local maxDistance = RANGE
	local nearestTarget

	for i, player in pairs(players) do
		if player.Character then
			local target = player.Character
			local distance = (hrp.Position - target.HumanoidRootPart.Position).Magnitude

			if distance < maxDistance and canSeeTarget(target) then
				nearestTarget = target
				maxDistance = distance
				humanoid.WalkSpeed = Speed

			end
		end
	end

	return nearestTarget
end

local function getPath(destination)
	local path = PathfindingService:CreatePath(pathParams)

	path:ComputeAsync(hrp.Position, destination.Position)

	return path	
end

local function attack(target)
	local distance = (hrp.Position - target.HumanoidRootPart.Position).Magnitude
	local debounce = false

	if distance > 5 then
		humanoid:MoveTo(target.HumanoidRootPart.Position)
	else
		local playerDeath = game.ReplicatedStorage.RemoteEvent.AttackEvent
		local player =game.Players:GetPlayerFromCharacter(target)
		if debounce == false then
			debounce = true
           --playerDeath:FireClient(player, npc)
			--npc.Head.AttackSound:Play() (no sound yet)
			attackAnim:Play()
			target.Humanoid.Health = 0
			attackAnim.Stopped:Wait()
			debounce = false
		end
	end
end


local function walkTo(destination)
	local path = getPath(destination)

	if path.Status == Enum.PathStatus.Success then
		for i, waypoint in pairs(path:GetWaypoints()) do
			path.Blocked:Connect(function()
				path:Destroy()
			end)

			if animPlaying == false then
				animPlaying = true
			end

			attackAnim:Stop()

			local target = findTarget()

			if target and target.Humanoid.Health > 0 then
				lastPos = target.HumanoidRootPart.Position
				attack(target)

				break
			else
				if waypoint.Action == Enum.PathWaypointAction.Jump then
					humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
				end

				if lastPos then
					humanoid:MoveTo(lastPos)
					humanoid.MoveToFinished:Wait()
					lastPos = nil
					humanoid.WalkSpeed = NorSpeed
					break
				else
					humanoid:MoveTo(waypoint.Position)
					humanoid.MoveToFinished:Wait()
					humanoid.WalkSpeed = NorSpeed
					
				end
			end
		end
	else
		return
	end
end


-- Add a stuck timer and a function to reset it
local stuckTimer = 0
local MAX_STUCK_TIME = 5 -- Adjust this value as needed (in seconds)
local lastXPosition = nil

local function resetStuckTimer()
	stuckTimer = 0
	lastXPosition = hrp.Position.X
end


local function isStuck()
	local currentXPosition = hrp.Position.X
	if lastXPosition then
		-- Check if the X position has changed significantly
		local deltaX = math.abs(currentXPosition - lastXPosition)
		print("DeltaX:", deltaX) -- Print the deltaX for debugging
		return deltaX < 0.1 -- Adjust this threshold as needed
	else
		return false
	end
end


local function patrol()
	local waypoints = workspace.Waypoints:GetChildren()
	local randomNum = math.random(1, #waypoints)
	local destination = waypoints[randomNum]

	-- Check if NPC is stuck
	if isStuck() then
		stuckTimer = stuckTimer + 0.2

		if stuckTimer >= MAX_STUCK_TIME then
			-- Reset the stuck timer and choose a new waypoint
			print("NPC Stuck! Resetting...")
			resetStuckTimer()
			destination = waypoints[math.random(1, #waypoints)]
		end
	else
		-- If not stuck, reset the timer
		resetStuckTimer()
		
	end

	walkTo(destination)
end


while Runservice.Heartbeat:Wait(0.1) do
	
	patrol()
end


local lastposX = hrp.Position.X
local lastposZ = hrp.Position.Z

local function OverwritePath()
	hrp.CFrame = CFrame.new(-669.841, -73.497, 270.572)
end

function roundNumber(number, numberDecimalPlaces)
	return tonumber(string.format("%." .. (numberDecimalPlaces or 0) .. "f", number))
end

spawn(function()
	while wait(0.3) do
		local count = 0
		if roundNumber(lastposX,1) == roundNumber(hrp.Position.X,1) then
			count += 1
		end
		if roundNumber(lastposZ,1) ==roundNumber(hrp.Position.Z,1) then
			count += 1
		end
		lastposX = hrp.Position.X
		lastposZ = hrp.Position.Z
		if count == 2 then
			OverwritePath()
		end
	end
end)

if the script is very messy I’m very sorry.

So some quick questions about the behavior and issues you’re facing, Can you clarify the scenario around teleporting it and not switching the waypoints n whatnot? Is it in the middle of chasing someone and you’re trying to update the pathing? Are you trying to change its path during a patrol?

Hi, I think i didnt clarify my problem clearly.
The problem I am facing probably this part of function didnt play after Ai is stuck for certain amount of time

spawn(function()
while wait(0.3) do
local count = 0
if roundNumber(lastposX,1) == roundNumber(hrp.Position.X,1) then
count += 1
end
if roundNumber(lastposZ,1) ==roundNumber(hrp.Position.Z,1) then
count += 1
end
lastposX = hrp.Position.X
lastposZ = hrp.Position.Z
if count == 2 then
OverwritePath()
end
end
end)

So,I try separate the script and it working fine.
Sorry if I cant give you more info, I’m outside right now.