Eye sight for monster

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.

1 Like

You use dotproduct!

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

Yeah. So I gave you the base code and now its on you to code the rest. I give you the concept and you formulate from it.

1 Like

But this is supposed to be an eye sight and this code is detecting the player everywhere around it…

Anyways

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

Wrote this on the website so pls fix the grammar.

Same problem. This is supposed to be an eye sight with a given fov. And the function is detecting all around the monster.

Something like this, but way less complicated (i know this is unreal engine):

My code is doing the same thing but I suppose I didn’t check it so issues are happening.

2 Likes

This does not determine whether something is obstructing the entity’s line of sight. A raycast is needed.

I really should look around the forum a bit more before asking these… Anyways. Thanks! After a little rework the code was working

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.