im trying to make an NPC that can pathfind around walls while also tracking the player, but it breaks around said walls. i tried to see what the problem was and the NPC’s state is running, even when its standing still. please help
local NPC = script.Parent
local NPCHumanoid = NPC.Humanoid
local NPCHumanoidRootPart = NPC.HumanoidRootPart
local function GetNearestPlayer()
local players = game.Players:GetPlayers()
local nearestplayer = nil
local nearestdistance = math.huge
for _,player in pairs(players) do
if player.Character and player.Character.HumanoidRootPart then
local char = player.Character
local distance = (char.HumanoidRootPart.Position - NPC.HumanoidRootPart.Position).Magnitude
if distance < nearestdistance then
nearestdistance = distance
nearestplayer = player
end
end
end
return nearestplayer,nearestdistance
end
--make enemies shoot a ray to see if the player is visible, if so, recalculate quickly like normal, if not, go around the wall.
local pathfindingservice = game:GetService("PathfindingService")
local function RaycastToPlayer(player)
local rayorigin = NPCHumanoidRootPart.Position
local raydirection = player.Character.HumanoidRootPart.Position - NPCHumanoidRootPart.Position
local raycastparams = RaycastParams.new()
raycastparams.FilterType = Enum.RaycastFilterType.Exclude
raycastparams.FilterDescendantsInstances = {NPC,game.Workspace.Chasers}
local raycastResult = workspace:Raycast(rayorigin,raydirection,raycastparams)
if raycastResult and raycastResult.Instance and raycastResult.Instance.Parent and game.Players:GetPlayerFromCharacter(raycastResult.Instance.Parent) then
return true
else
return false
end
end
local function Move(player,distance)
local path = pathfindingservice:CreatePath()
path:ComputeAsync(NPCHumanoidRootPart.Position,player.Character.HumanoidRootPart.Position)
local velocity = player.Character.HumanoidRootPart.AssemblyLinearVelocity
local waypoints = path:GetWaypoints()
for i=1,#waypoints do
print(i)
local waypoint = waypoints[i]
print("1")
if waypoint.Action == Enum.PathWaypointAction.Jump and NPCHumanoid:GetState() ~= Enum.HumanoidStateType.Jumping and NPCHumanoid:GetState() ~= Enum.HumanoidStateType.Freefall then
NPCHumanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
print("2")
if RaycastToPlayer(player) then
print("no wall")
NPCHumanoid:MoveTo(waypoint.Position + velocity)
print("no wall2")
else
print("wall")
print(waypoint.Position)
NPCHumanoid:MoveTo(waypoint.Position)
print("wall2")
repeat
wait()
print(NPCHumanoid:GetState())
until
NPCHumanoid:GetState() ~= Enum.HumanoidStateType.Running
print("4")
end
end
end
while wait(0.1) do
local player,distance = GetNearestPlayer()
if player and player.Character then
Move(player,distance)
end
end