I’m working on a game where I want the enemies to prioritize attacking a specific humanoid because it represents food they want to eat. However, I also want the enemies to attack nearby players. My challenge is figuring out how to make the enemies focus primarily on the humanoid but still attack players if they’re close.
Does anyone have any ideas on how I would achieve this? Here is the current enemy script that attacks nearby players:
--// SERVICES
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
--------
local humanoid = script.Parent
local root = humanoid.Parent.PrimaryPart
root:SetNetworkOwner(nil)
local targetDistance = script.Parent:GetAttribute("TargetDistance")
local stopDistance = script.Parent:GetAttribute("StopDistance") --Stop moving when close to player
local damage = script.Parent:GetAttribute("Damage")
local attackDistance = script.Parent:GetAttribute("AttackDistance")
local attackWait = script.Parent:GetAttribute("AttackWait")
local lastAttack = tick() --the seconds of time it is since last attack
--//ANIMATIONS
local animator = humanoid:WaitForChild("Animator")
local runAnim = script:WaitForChild("Chase")
local runTrack = animator:LoadAnimation(runAnim)
-------
function FindNearestPlayer()
local plrs = Players:GetPlayers()
local nearestPlr = nil
local distance = nil
local direction = nil
for _, player in pairs(plrs) do
local character = player.Character
if character then
local distanceVector = player.Character.HumanoidRootPart.Position - root.Position
if not nearestPlr then
nearestPlr = player
distance = distanceVector.Magnitude
direction = distanceVector.Unit
elseif distanceVector.Magnitude < distance then
nearestPlr = player
distance = distanceVector.Magnitude
direction = distanceVector.Unit
end
end
end
return nearestPlr, distance, direction
end
RunService.Heartbeat:Connect(function()
local nearestPlr, distance, direction = FindNearestPlayer()
if nearestPlr then
if distance <= targetDistance and distance > stopDistance then
--runs when moving
if not runTrack.IsPlaying then
runTrack:Play()
end
humanoid:Move(direction)
else
--runs when standing still
if runTrack.IsPlaying then
runTrack:Stop()
end
humanoid:Move(Vector3.new())
end
if distance <= attackDistance and tick() - lastAttack >= attackWait then
lastAttack = tick()
nearestPlr.Character.Humanoid:TakeDamage(damage)
end
end
end)