So I want to make an NPC that follows you and when it's close enough it kills you, but for some weird reason the if statement doesn't fire. I replaced the less than sign with the greater than sign, and that seemed to work but it kills you anywhere, please help.
if (script.Parent.HumanoidRootPart.Position - v.HumanoidRootPart.Position).magnitude < 10 then v.Humanoid:TakeDamage(100) wait(1.5) d = false end
Full script:
local d = false while wait() do for i, v in pairs(workspace:GetChildren()) do if v:FindFirstChild("HumanoidRootPart") and (script.Parent.HumanoidRootPart.Position - v.HumanoidRootPart.Position).magnitude < 1000 and v ~= script.Parent and v.Humanoid.DisplayName ~= "Duck" and v:FindFirstChild("HumanoidRootPart").Anchored ~= true and v.Humanoid.Health ~= 0 then if not d then d = true script.Parent.Humanoid:MoveTo(v.HumanoidRootPart.Position) if (script.Parent.HumanoidRootPart.Position - v.HumanoidRootPart.Position).magnitude < 6 then v.Humanoid:TakeDamage(100) wait(1.5) d = false end end end end end script.Parent.Humanoid.Died:Connect(function() script:Destroy() end)
This is most likely due to you only checking the condition once.
Since your code is not in a function nor being called upon, it is only going to check the condition once when the script loads and it will not check it again.
There are two ways of going around this; that is by using a loop or an event. I would not recommend using a loop for this as it will use unnecessary resources when the player is standing still.
The Humanoid has a Running event which will fire whenever the player moves. I, however, prefer to use the method GetPropertyChangedSignal for the MoveDirection property of the Humanoid. The reason for this- is that the Running event, for some reason, fires twice when you start running. (usually not a big deal; I still rather use the MoveDirection as it seems to work better). You can use whichever you want.
local function running() if (script.Parent.HumanoidRootPart.Position - v.HumanoidRootPart.Position).magnitude < 10 then v.Humanoid:TakeDamage(100) wait(1.5) d = false end end Humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(function() if Humanoid.MoveDirection ~= Vector3.new(0,0,0) then if not Character:GetAttribute("Running") then -- debounce Character:SetAttribute("Running", true) game:GetService("RunService"):BindToRenderStep("Moving", 1, running) end else game:GetService("RunService"):UnbindFromRenderStep("Moving") Character:SetAttribute("Running", false) end end)