Make pathfinding change when damage is taken

I’ve been working on a monster AI and I’ve been wondering how I can make it retreat when it takes too much damage. Anyone know how I can go about it?

local hum = script.Parent:WaitForChild("Humanoid")
local torso = script.Parent:WaitForChild("Torso")
local PathfindingService = game:GetService("PathfindingService")
local Retreat = workspace.RetreatPoint

local function GetPath(destination)
	local path = PathfindingService:CreatePath()
	path:ComputeAsync(torso.Position, destination)
	return path
end

local function move(destination)
	local path = GetPath(destination)

	for index, waypoint in pairs(path:GetWaypoints()) do
		hum:MoveTo(waypoint.Position)
		hum.MoveToFinished:Wait()
	end
end

local function patrol()
	local Points = workspace.Points:GetChildren()
	local RandomPoint = math.random(1, #Points)
	move(Points[RandomPoint].Position)
end

while wait(0.5) do
	patrol()
end
3 Likes
  1. Please fix the format of your code.

  2. Follow these guidelines for making posts:

    “1. What do you want to achieve? Keep it simple and clear!
    2. What is the issue? Include screenshots / videos if possible!”

I know its lame, but help here is completely voluntary, so asking us to do ALL the work is a tall order. Thanks

Sorry, it’s my first time posting!

1 Like

Define too much damage.

1 Like

like if it loses 1/4 of it’s health

1 Like
local hum:Humanoid? = script.Parent:WaitForChild("Humanoid")
local torso = script.Parent:WaitForChild("Torso")
local PathfindingService = game:GetService("PathfindingService")
local Retreat = workspace.RetreatPoint
function Calculate14(health:number?):number?
	return (hum.Health / 4)
end
local function GetPath(destination)
	local path = PathfindingService:CreatePath()
	path:ComputeAsync(torso.Position, destination)
	return path
end
function RetreatBack()
	hum:MoveTo(Retreat.Position)
end
local function move(destination)
	local path = GetPath(destination)

	for index, waypoint in path:GetWaypoints() do
		hum:MoveTo(waypoint.Position)
		hum.MoveToFinished:Wait()
		if hum.Health <= Calculate14() then
			task.spawn(RetreatBack)
			break
		end
	end
end

local function patrol()
	local Points = workspace.Points:GetChildren()
	local RandomPoint = math.random(1, #Points)
	move(Points[RandomPoint].Position)
end

while task.wait(0.5) do
	if hum.Health >= Calculate14() then
		patrol()
	end
end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.