Now first off, I’d like to say that I am new and this is my first ever post so if there is any post(s) related or may help solve the issue, please let me know!
This mostly happens when I increase my WalkSpeed above or close to 16.
Here is my script:
-- Variables --
local NPC = script.Parent
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local PathfindingService = game:GetService("PathfindingService")
-- Settings --
script.Parent.PrimaryPart:SetNetworkOwner(nil) -- Was just a test, but I think things were a bit improved with it.
local AttackDamage = 25 -- How much damage the NPC will deal
local AttackCooldownTime = 1 -- How long til he can attack again
local AttackCooldown = false -- A debounce variable
local Range = 50 -- Distance of how far the NPC can reach you
local FocusedOnTarget = false -- A debounce variable to check if the NPC is focused on a target
local NPCSpeed = 16 -- How fast the NPC will walk
-- Functions --
NPC.Humanoid.WalkSpeed = NPCSpeed
function moveRandomDirection()
local randomX = math.random(-24,24)
local randomZ = math.random(-24,24)
NPC.Humanoid:MoveTo(NPC.HumanoidRootPart.Position + Vector3.new(randomX, 0, randomZ))
end
function ChasePlr()
for _, player in pairs(Players:GetPlayers()) do
local Character = player.Character
local Distance = (Character.HumanoidRootPart.Position - NPC.HumanoidRootPart.Position).magnitude
if Distance <= Range then
-- Player is in Range of NPC!
local Path = PathfindingService:CreatePath()
Path:ComputeAsync(NPC.HumanoidRootPart.Position, Character.HumanoidRootPart.Position)
local Waypoints = Path:GetWaypoints()
FocusedOnTarget = true
for _, waypoint in pairs(Waypoints) do
NPC.Humanoid:MoveTo(waypoint.Position)
NPC.Humanoid.MoveToFinished:Wait()
end
else
-- Is not in range of NPC!
FocusedOnTarget = false
end
end
end
function AttackPlr(hitPart)
if not AttackCooldown and hitPart.Parent.Humanoid then
AttackCooldown = true
hitPart.Parent.Humanoid.Health -= AttackDamage
wait(AttackCooldownTime)
AttackCooldown = false
end
end
-- Connect functions --
RunService.Heartbeat:Connect(ChasePlr)
NPC.HumanoidRootPart.Touched:Connect(AttackPlr)
NPC.Head.Touched:Connect(AttackPlr)
while wait(5) do
if not FocusedOnTarget then
moveRandomDirection()
end
end