I am making an NPC detection thing and I know that I can just use magnitude and raycasting to see if an NPC can detect a player, I was thinking I would have to use RunService to do this but that seems like it would be a bit inefficient performance wise. The magnitude would not be costly I don’t think but if there is a player within range that means it would be raycasting every frame which doesn’t seem too performant. Any better ways or let me know if this isn’t actually very performance inefficient?
NPC detection can be something like
local RunService = game:GetService("RunService")
local players = game:GetService("Players")
local NPC = script.Parent -- Assuming this script is a child of the NPC
local detectionRadius = 50
local checkInterval = 0.5
local lastCheckTime = tick()
local function detectPlayers()
for _, player in ipairs(players:GetPlayers()) do
local character = player.Character
local humanoidRootPart = character and character:FindFirstChild("HumanoidRootPart")
if humanoidRootPart then
local distance = (NPC.Position - humanoidRootPart.Position).magnitude
if distance <= detectionRadius then
-- Further checks (e.g., raycasting) can go here if needed
print(player.Name .. " is within detection radius.")
end
end
end
end
RunService.Heartbeat:Connect(function()
if tick() - lastCheckTime >= checkInterval then
lastCheckTime = tick()
detectPlayers()
end
end)
So you’re just suggesting adding a check wait time?
1 Like
That could be it as the run service or something like heart beat every frame can be costly inefficient wise
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.