Hello. Recently I have been attempting to make a horror game, and my NPC keeps bugging out in ways such as;
Walking into walls
Randomly turning around while pathfinding to the player
Here is the code for his AI, which was made following a tutorial by GnomeCode
Here’s the video
My code (ServerScript):
local nycto = game.Workspace.nycto
local humanoid = nycto.Humanoid
local walkAnim = humanoid:LoadAnimation(nycto.Walk)
local runAnim = humanoid:LoadAnimation(nycto.Run)
local pathfinding = game:GetService("PathfindingService")
local chasing = false
local walking = false
local function canSeeTarget(target)
local origin = nycto.HumanoidRootPart.Position
local direction = (target.HumanoidRootPart.Position - nycto.HumanoidRootPart.Position).unit * 200
local ray = Ray.new(origin, direction)
local hit, pos = workspace:FindPartOnRay(ray, nycto)
if hit then
if hit:IsDescendantOf(target) then
return true
end
else
return false
end
end
local function findTarget()
local players = game.Players:GetPlayers()
local maxDistance = 75
local nearestTarget
for index, player in pairs(players) do
if player.Character then
local target = player.Character
local distance = (nycto.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
if distance < maxDistance and canSeeTarget(target) then
nearestTarget = target
maxDistance = distance
end
end
end
return nearestTarget
end
local function getPath(destination)
local pathParams = {
["AgentHeight"] = 17,
["AgentRadius"] = 3,
["AgentCanJump"] = false
}
local path = pathfinding:CreatePath(pathParams)
path:ComputeAsync(nycto.HumanoidRootPart.Position, destination.Position)
return path
end
local function attack(target)
local distance = (nycto.LeftKnee.Position and nycto.RightKnee.Position - target.HumanoidRootPart.Position).Magnitude
if distance > 5.5 then
humanoid:MoveTo(target.HumanoidRootPart.Position)
else
target.Humanoid.Health = 0
end
end
local function walkTo(destination)
local path = getPath(destination)
if path.Status == Enum.PathStatus.Success then
for index, waypoint in pairs(path:GetWaypoints()) do
local target = findTarget()
if target then
humanoid.WalkSpeed = 50
attack(target)
break
else
nycto.Humanoid.WalkSpeed = 16
humanoid:MoveTo(waypoint.Position)
humanoid.MoveToFinished:Wait()
end
end
else
humanoid:MoveTo(destination.Position - (nycto.HumanoidRootPart.CFrame.LookVector * 70))
end
end
local function patrol()
local waypoints = workspace.waypoints:GetChildren()
local randomNum = math.random(1, #waypoints)
walkTo(waypoints[randomNum])
end
while wait() do
patrol()
end
If anyone has any clue what could be happening, help would be greatly appreciated.
Also, here’s another user’s post who has a similar problem, which followed the same tutorial
Obviously, the tutorial that we followed must’ve not been the best one, so, what could be done to fix these problems?