Hello dear developers. I’m trying to build my own horror game to make players have fun.
I’m building a killer that chases nearest players to kill them. I scripted the NPC with my own pathfinding code.
local PathfindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local NPC = script.Parent
local NPCHumanoid = NPC.Zombie
local NPCHRP = NPC.HumanoidRootPart
local CurrentTarget = nil
local CurrentPath = nil
local IsFollowing = false
function GetNearestPlayer()
local NearestPlayer = nil
local ShortestDistance = math.huge
for _,v in pairs(Players:GetPlayers()) do
if v and v.Character and v.Character:FindFirstChild("Humanoid") then
local Distance = (v.Character.HumanoidRootPart.Position - NPCHRP.Position).Magnitude
if Distance <= 100 and Distance < ShortestDistance then
ShortestDistance = Distance
NearestPlayer = v
end
end
end
return NearestPlayer
end
function ComputePath(Pos)
local Path = PathfindingService:CreatePath({
AgentRadius = 2,
AgentHeight = 5,
AgentCanJump = true,
AgentJumpHeight = 7,
AgentMaxSlope = 45
})
Path:ComputeAsync(NPCHRP.Position, Pos)
if Path.Status == Enum.PathStatus.Success then
return Path
else
warn("Path could not be computed")
return nil
end
end
function FollowPath(Path)
IsFollowing = true
for _, Waypoint in ipairs(Path:GetWaypoints()) do
NPCHumanoid:MoveTo(Waypoint.Position)
if Waypoint.Action == Enum.PathWaypointAction.Jump then
NPCHumanoid.Jump = true
end
local Success = NPCHumanoid.MoveToFinished:Wait()
if not Success then
break
end
end
IsFollowing = false
end
task.spawn(function()
while task.wait(0.1) do
if not IsFollowing then
local Player = GetNearestPlayer()
if Player and Player.Character and Player.Character:FindFirstChild("HumanoidRootPart") then
local TargetPosition = Player.Character.HumanoidRootPart.Position
local Path = ComputePath(TargetPosition)
if Path then
if CurrentPath then
CurrentPath:Destroy()
end
CurrentPath = Path
FollowPath(Path)
end
end
end
end
end)
but the main problem is the ai only chases old waypoints but not new way points.
for an example when player moves far away from the NPC the NPC only walks to old waypoints to reach the player. this almost becomes impossible for NPC to kill players.
if you guys still do not understood, heres an example of video: