I’m trying to make an eye sight for a monster in my game, so it will only attack you when you it sees you, but whatever I try it doesn’t seems to work.
Here is my code so far:
local eyeSight = --part
local fov = 100 --filed of view
local range = 20 --range
local rayNum = 10 --number of rays
while true do
wait()
for i=-rayNum/2, rayNum/2 do -- -5 to 5
local ray = Ray.new(eyeSight.Position, eyeSight.CFrame.LookVector +Vector3.new(i*(rayNum/fov),0,0) * range)
local hit = workspace:Raycast(ray.Origin, ray.Direction)
if hit and hit.Instance.CanCollide == true then
print(hit)
end
end
end
So far the rays detect me, but not in the given fov and not constatnly. Even when I raise the range the rays still only detetct me when I’m very close.
This is because in this configuration, the rays diverge out so accuracy is lost the further away something is. Perhaps this is not the most practical method of eye sight.
local MonsterHRP = -- Monster's HRP's Position
local PlayersHRP = -- Players position.
local Dot = math.acos((MonsterHRP.Position-PlayersHRP.Position).Unit:Dot(PlayersHRP.CFrame.LookVector))
if Dot < fov then
-- do smthing
endd
Yeah. So I kinda need to detect all players and not just one. And also the other zombies. Sorry for not meantioning that. And I think putting this into a loop with all the players and monsters would make the game very laggy
local MonsterHRP = -- Monster's HRP's Position
local FOV = 100
local Range = 50
local function GetClosestPlayer()
local plr,dist = nil,Range
for i,v in pairs(game.Players:GetPlayers()) do
if v:DistanceFromCharacter(MonsterHRP.Position) <= dist then
plr = v
dist = v:DistanceFromCharacter(MonsterHRP.Position)
end
end
return plr
end
while Monster do
local PlayersHRP = GetClosestPlayer()
local Dot = math.acos((MonsterHRP.Position-PlayersHRP.Position).Unit:Dot(PlayersHRP.CFrame.LookVector))
if math.abs(Dot) < math.rad(FOV) then
-- do smthing
end
task.wait()
end