I was working on a pathfinding agro zombie type NPC just to dip my fingers in pathfinding and ray casting.
-- variables used in other functions
local pathService = game:GetService("PathfindingService")
local human = script.Parent.Humanoid
local moving = nil
local RootPart = script.Parent.HumanoidRootPart
local targets = {}
-- function
function FindTarget()
local distance = 30
local target = nil
for i, v in pairs(game.Workspace:GetChildren()) do
local findHuman = v:FindFirstChild("Humanoid")
local findRoot = v:FindFirstChild("HumanoidRootPart")
if findHuman and findRoot and v.Name ~= script.Parent.Name then
-- checks the workspace for anything containing a humanoid and humanoid root part
if (RootPart.Position - findRoot.Position).Magnitude < distance and findHuman.Health ~= 0 then
-- check if distance between the root part of the character and NPC is less than the distance of 30 studs and the Health of the character is not 0
print("Target Found")
table.insert(targets, findRoot)
-- raycasting stuff
local newRayParams = RaycastParams.new()
newRayParams.FilterDescendantsInstances = {script.Parent}
newRayParams.FilterType = Enum.RaycastFilterType.Blacklist
local newRay = game.Workspace:Raycast(script.Parent.Head.Position, (findRoot.Position - RootPart.Position).Unit * distance, newRayParams)
if newRay ~= nil then
hitPart = newRay.Instance
end
if hitPart then
print("ray has hit: " .. hitPart.Parent.Name)
end
end
end
end
end
What this is supposed to do is filter out the model the script is in (so the zombie NPC) and detect nearby players (within 30 studs).
** On line 29 of this post, I have an if statement to check and see if the ray has intersected something (or so I think that's how it works from the wiki) and the problem is - when I put a wall directly in front of the zombie's head, It still detects "legoguy939" which is my character, even though the ray would logically intersect the part. **

1 comment
Well it turns out I am still as rusty as ever. In studio I kept moving a part in front of the NPC's face - thus - there should be a new intersection......I did not realize I was moving it client-side only....Thus, that was the issue - and this script works fine but is probably not very optimized.