How do i make my enemy ai have a certain distance it can see me?

Ello everyone!
I have been trying to make a enemy ai for a while now and so far its going great, the script under here is working fine as it makes my custom rigged ai chase me. However it can see me from everywhere in the game and will start to chase me, it does not matter where I am, and i have no clue how to give it a view distance.

Script:

local enmhum = script.Parent.Humanoid
local anm = script.Parent.Humanoid.Animation
local load = script.Parent.Humanoid:LoadAnimation(anm)

while wait() do
for i,v in pairs (game.Players:GetChildren()) do
local character = game.Workspace:WaitForChild(v.Name)
enmhum:MoveTo(character.PrimaryPart.Position)
load:Play()
enmhum.MoveToFinished:Wait(1)
load:Stop()
end
end

Some quick notes:
I am new to using this dev forum so my bad if I did something wrong, also I am very new to scripting and the script abov is not entirely mine but i have wasted a lot of time learning it and watching yt tutorials, which got me no where.

2 Likes

Hello! You can use Raycasting to check if the player is behind a wall or just an object. If the raycast doesn’t return nil it means it has found an object, and in that case just don’t make the NPC chase the player.
If you want to check how far the player is from the NPC you can use magnitude.

2 Likes

I think GnomeCode made a video about this, it was in his Making Teddy series, watch his channel he is quite good at explaining it.

1 Like

Hey you can write a script with this :

local Cheese = "Delicios!" 
1 Like

Aight i will try to look into this

1 Like

I have tried to follow that video but it didnt really work out for me cause i got confused at a certain point, however i can look into it and try again

1 Like

Oh, thank you, I didn’t know :+1:

1 Like

No problem, I also didnt know about this after 1 month