AI script getting stuck

Hello,
I’m making an AI Script for my game, and I have a problem. The code works fine outside but my story game is inside a house. Basically, the NPC keeps getting stuck. For example, if there is a wall and the player is on the otherside, the npc will try to directly go to the player. I know this is possible, because I’ve seen it in other story games. I need it so that the npc doesn’t get stuck on a wall and instead it goes around it.
here is my current script:

local Monster = script.Parent
local humanoid = Monster.Humanoid
local PlayerService = game:GetService('Players')

local TrackingStatus = false

local function GetNewPlayer()
	print("Getting New Player")
	return PlayerService:GetPlayers()[math.random(1, #PlayerService:GetPlayers())]
end

local function TrackNewPlayer(Target)
	print("Tracking New Target")
	game.ReplicatedStorage.ShakeCamera:FireAllClients()
	for _, Player in pairs(game.Players:GetPlayers()) do
		if Player.Character and Player.Character.Humanoid.Health > 0 then
			game.ServerStorage.HorrorGui:Clone().Parent = Player.PlayerGui
		end
	end
	Monster.TeleportSpirit.Fire.Enabled = true
	wait(1)
	Monster.HumanoidRootPart.CFrame = Target.HumanoidRootPart.CFrame - Vector3.new(0,0,20)
	wait(1)
	Monster.TeleportSpirit.Fire.Enabled = false
	local function Track()
		while TrackingStatus do
			if not TrackingStatus then break end
			if Target.Humanoid.Health == 0 then break end
			humanoid:MoveTo(Target.HumanoidRootPart.Position)
			wait()
		end
	end
	coroutine.resume(coroutine.create(Track))
end

while true do
	print("AI Running")
	while #PlayerService:GetPlayers() == 0 do wait() end
	local Target = GetNewPlayer()
	local Character = Target.Character
	if Character then
		if Character.Humanoid.Health > 0 then
			TrackingStatus = true
			TrackNewPlayer(Character)
			wait(15)
			TrackingStatus = false
			print("Tracking Ended")
		end
	end
	wait()
end

Thanks for an help!

I’ve looked at the pathfinding service but I’m not sure how to implement it with this script.

2 Likes

What you would wanna do is loop through like 3 of the points generated by the pathfinding service within the Track() function. You would first use MoveTo() to move the character towards the first point and wait until the character is close enough, then iterate to the next point. After those 3 points have been iterated through, you can generate 3 new points to account for player the player moving. *3 is just an arbitrary number, you can use more or less.

1 Like