I want to achieve an NPC that will start following you when it sees you, using raycast works, but the follow script doesn’t seem to activate, I tried multiple other scripts to see if they could work, but nope, nothing.
Is the NPC the problem? It doesn’t seem to move, but this is the raycast script
local DISTANCE = 20 – How far the NPC can see.
local Players = game:GetService(“Players”)
local origin = script.Parent.Head – Origin of where the raycast is.
while wait() do
local ray = Ray.new(origin.Position, origin.CFrame.lookVector * DISTANCE) -- Calculating the raycast.
local hit = workspace:FindPartOnRay(ray, origin.Parent) -- Creating a ray to see what the npc sees.
if hit then
for _, player in pairs(Players:GetPlayers()) do -- We're going to loop through all players to see if the npc sees any of them.
if player.Character and player.Character:IsAncestorOf(hit) then
-- Handle what happens here.
print("I see " .. player.Name)
break
end
end
end
end
Any ideas on how to add a follow script on the little guy? Help is apreciated
I tested this, and it worked for me. Note that your code is inefficient, as there is no need to loop through all the players. When the ray hits a part, you can use the function game.Players:GetPlayerFromCharacter(instance) to check if it’s a player.
As for your code not working, note that the player needs to be right in front of the NPC (up to DISTANCE) for this to work. Also make sure that the NPC head part has FrontSurface facing toward the correct direction.
The raycast isn’t the problem, it’s the code that makes it follow you, it can adknowledge it saw you (got the printed message in the output) but it still doesn’t move.
Thank you, the NPC is finally following the player when it falls on the raycast, if it falls out it stops chasing it, but I know how to fix it, thanks a lot for the help.