Use magnitude without detecting through walls?

Hi, so for my game I want to have an npc detect if a player is within a certain magnitude, but it will detect them through a wall. I want to know how I can use magnitude without detecting the player on the other side of the wall. Thanks!

you could always just constantly cast a ray to them and then form a vector from the intersection point and the origin then get the magnitude from that

The way I usually do this is to get the player as you normally would with a loop (I do this first to prevent unnecessary raycasting which can be detrimental), but then raycast from the npc to the player and see if any part is returned that isn’t the player.

Well, how can i have a raycast see the area around the npc, i thought i would only face one direction?

Raycasts are completely independent of anything else. You give it an origin and a direction. You can iterate over players using an ipairs() for loop, get their distance from the npc like you normally would and if it’s within your parameters, do a raycast from the npc in the direction of the player which would be the same as your vector which you get like this:
local vector = (character.HumanoidRootPart.Position - npc.Position). With this you can get Magnitude and this vector is also the direction of the raycast which you would do like so: workspace:Raycast(npc.Position, vector, params). Note it’s crucial you subtract the vectors in that order to get the direction facing the right way otherwise it’ll be the opposite way.

1 Like

Alright, i will try to do this, thanks!

1 Like

It does actually work, I’ve made a tutorial on this btw

I tried it and it seems to only detect when the player is behind the npc ?

Edit: Also nah is the name of the array

	for i,v in pairs(game.Workspace:GetChildren()) do
		local player = game.Players:GetPlayerFromCharacter(v)
		if player then
			local vector = (v.Torso.Position - script.Parent.Head.Position)
			if vector.magnitude <= 20 then
				local raypa = RaycastParams.new()
				raypa.FilterDescendantsInstances = nah
				raypa.FilterType = Enum.RaycastFilterType.Whitelist
				local result = workspace:Raycast(script.Parent.Head.Position,vector,raypa)
				if result then
					print(result)
				end
			end
		end
	end
end
1 Like

Nevermind, I put it on whitelist instead of blacklist, thanks!