How can I raycast in every direction?

Im trying to make a NPC that can only see players if there in his view (a circle) and I tried to do this with raycast and when I ran the code it kept only casting a ray in 1 line.

My code is:

local RP = RaycastParams.new()
RP.RespectCanCollide = true

RP.FilterDescendantsInstances = {script.Parent}
RP.FilterType = Enum.RaycastFilterType.Exclude
function FindPlayerWithRay()
	local diry = 0
	for i=1,360,1 do
		local rayResult = workspace:Raycast(script.Parent.HumanoidRootPart.Position,Vector3.new(0,0,diry),RP)
		if rayResult and rayResult.Instance then
			local plr = game.Players:GetPlayerFromCharacter(rayResult.Instance.Parent)
			if plr then
				print(plr)
			end
		end
		-- this is just to see where the ray is hitting
		if rayResult and rayResult.Position then
			local p = Instance.new("Part")
			p.Shape = Enum.PartType.Ball
			p.Size = Vector3.new(1,1,1)
			
			p.CFrame = CFrame.new(rayResult.Position,Vector3.new(0,0,diry))
			p.Parent = workspace
			p.CanCollide=false
			p.Anchored = true
		end
		
		diry=i
		print(diry)
	end
end

What did I do wrong?

It would be MUCH easier and more efficient to just loop through all the players, check their distance, and if they are within range, cast a ray towards them to see if the NPC can see them.

1 Like

I shouldve thought of this earlier. This worked when I tried it.

1 Like

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