I have an NPC who follows the player’s character and attacks it, but now I want to create a friendly NPC who follows the player’s character, and if an NPC branded as an enemy is nearby, the friendly NPC will then follow the enemy and attack it. Should the enemy be killed, the friendly NPC will then resume following the player.
I, however, am unaware of how to let the NPC follow the player and then engage the enemy without alternating uncontrollably between both actions, or any other form of unwanted behaviour. I would like to know how I could create this friendly NPC, preferably using the code I already have for the hostile NPC.
Here is said code:
local players = game:GetService("Players")
local sets = script.Parent.Settings
local shouldStop = sets.ProximityStop
local stopStudAmount = shouldStop.ProximityValue.Value
local hrp = script.Parent.HumanoidRootPart
local anim = script.Parent.Humanoid:LoadAnimation(script:FindFirstChildOfClass("Animation"))
local damage = script.Parent.Damage.Script
local humanoid = script.Parent.Humanoid
local ogspeed = humanoid.WalkSpeed
local canattack = true
local function Follow()
local distance = sets["Maximum Distance"].Value
for _, player in ipairs(players:GetPlayers()) do
local char = player.Character or player.CharacterAdded:Wait()
local target = char:FindFirstChild("HumanoidRootPart")
if target then
if (target.Position - hrp.Position).Magnitude <= distance then
script.Parent.Humanoid:MoveTo(target.Position, target)
if (hrp.Position - target.Position).Magnitude < stopStudAmount and shouldStop.Value and canattack then
canattack = false
humanoid.WalkSpeed = 0
anim:Play()
task.wait(0.2)
damage.Enabled = true
task.wait(0.3)
humanoid.WalkSpeed = ogspeed
damage.Enabled = false
canattack = true
end
end
end
end
end
while task.wait(0.2) do
Follow()
end