I am trying to make my NPC pathfind back until it is not close to a player in magnitude
For example: Magnitude between player and NPC is less than 12
What to do: Go back until magnitude is more than 12 while avoiding walls (To not get trapped to the wall so the player cannot kill)
For example 2: Magnitude is more than 12 and less than 15
What to do: Just stop moving to shoot (Melee range of player is 9)
Tried figuring it out but I’m afraid I will make a lot of errors
local TargetNonPlayers = true
local Epitaph = .187 -- Do not mess this up or aiming will be terrible
local Character = script.Parent
local PFS = game:GetService("PathfindingService")
local path = PFS:CreatePath()
local waypoints
local debounce = false
local Tool = Character:FindFirstChildWhichIsA('Tool')
local Melee = false
local MeleeRangeAttack = 9
local RangedAttackRange = 384
local UseTool = true
-- The examples explain this
while true do
local targetplr = findTarget() -- finds the closest target
if targetplr then
path:ComputeAsync(Character.HumanoidRootPart.Position, targetplr.HumanoidRootPart.Position)
waypoints = path:GetWaypoints()
for i, waypoint in pairs(waypoints) do
if targetplr:FindFirstChild('Head') and UseTool and Character:FindFirstChildWhichIsA('Tool') then
Tool = Character:FindFirstChildWhichIsA('Tool')
local DistanceMag = (Character.HumanoidRootPart.Position - targetplr.HumanoidRootPart.Position).Magnitude
spawn(function()
if Melee == true then
if DistanceMag < MeleeRangeAttack * 2 then
local Future = targetplr.HumanoidRootPart.CFrame + (targetplr.HumanoidRootPart.Velocity * Epitaph + Vector3.new(0, .1, 0))
Character.PrimaryPart.CFrame = CFrame.lookAt(Character.PrimaryPart.CFrame.Position, Vector3.new(Future.Position.X, Character.PrimaryPart.CFrame.Position.Y, Future.Position.Z))
if DistanceMag < MeleeRangeAttack then
Tool:Activate()
end
end
else
if DistanceMag < RangedAttackRange then
local Future = targetplr.HumanoidRootPart.CFrame + (targetplr.HumanoidRootPart.Velocity * Epitaph + Vector3.new(0, .1, 0))
Character.PrimaryPart.CFrame = CFrame.lookAt(Character.PrimaryPart.CFrame.Position, Vector3.new(Future.Position.X, Character.PrimaryPart.CFrame.Position.Y, Future.Position.Z))
Character.Humanoid.TargetPoint = Future.Position
Tool:Activate()
end
end
end)
end
if waypoints[i].Action == Enum.PathWaypointAction.Jump then
Character.Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
Character.Humanoid:MoveTo(waypoint.Position)
Character.Humanoid.MoveToFinished:Wait()
end
else
Character.Humanoid.TargetPoint = Vector3.new(0, 0, 0)
task.wait()
end
end