I need help with my AI

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.

Are you sure the NPC isn’t anchored?

Also, make sure the NPC’s head is inside a character model. Otherwise, this raycast will ignore everything inside workspace.

Every part is unanchored, yet he is still as a rock, the raycast works, but no movement.

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.

Here you go.

https://developer.roblox.com/en-us/api-reference/function/Humanoid/MoveTo

https://developer.roblox.com/en-us/api-reference/function/Humanoid/Move

Any errors? I’m sure the problem doesn’t occur in the script but in the NPC model itself, it’s safe to assume it has a humanoid right?

Yes, it has a humanoid, but, no error messages.

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.

1 Like