How to detect if a HumanoidRootPart is in fov and distance of player?

Working on a punching system but I don’t wanna use a hitbox touched event so instead, I’m using magnitude and player FOV. I came across this, however, it isn’t working for me. Here is my script.

local db = false
local combo = 0
local event = script.Parent:WaitForChild("Punch")
local c = script.Parent.Parent
event.OnServerEvent:Connect(function()
	
	if db then return end
	if c.Humanoid.Health <= 0 then return end
	if c.Stunned.Value == true or c.IFrame.Value == true or c.AbilityBeingCast.Value == true then return end --this is just some checkups on the player, don't worry about this
	if combo == 0 then
		print("combo 0")
		for i, v in pairs(workspace:GetChildren()) do
			if v:FindFirstChild("Humanoid") then
				if v ~= c then
					print("humanoid found")
					local hrp = c.HumanoidRootPart
					local enemyHRP = v.HumanoidRootPart
					local enemyHum = v.Humanoid
					local magn = (hrp.Position - enemyHRP.Position).magnitude
					local radius = 5
					local angle = 45
					if magn <= radius then
						print("in radius")
						local dot = hrp.Position:Dot(enemyHRP.Position)
						print("dot") --prints this and every print() up to this
						if dot >= 0 and dot <= math.cos(math.rad(angle)) then
							print("humanoid in range") --never reaches this??
						end
						
					end
				end

			end
			
		end 
		
	end
	
end)

Roblox has a built-in function that allows you to check if some position is on-screen if you want to take a less mathematical approach:

https://developer.roblox.com/en-us/api-reference/function/Camera/WorldToScreenPoint

					if magn <= radius then
						print("in radius")
                        local vector, isOnScreen = camera:WorldToScreenPoint(hrp.Position)
						if isOnScreen then
                            print('humanoid in range')
                        end
					end

my game is in 3rd person so it damages people if they are behind them with this method

sorry for not stating it in the post, but I’m trying to make it only damage people in front of them as well, which is why I mentioned the player’s FOV

Ahh okay, hmm.
I wonder if you could use ToObjectSpace to determine whether something is in front of the player or not:

local runService = game:GetService('RunService')

local humanoidRootPart: BasePart = script.Parent:WaitForChild('HumanoidRootPart')
local part = workspace:WaitForChild('ToCheck')

runService.RenderStepped:Connect(function()
	local hrpRelative = humanoidRootPart.CFrame:ToObjectSpace(part.CFrame)
	local partX = hrpRelative.Z
	local _, isOnScreen = workspace.CurrentCamera:WorldToScreenPoint(part.Position)
	if isOnScreen then
		if partX < 0 then
			print('In front')
		else
			print('Not in range!')
		end
	else
		print('Not in range!')
	end
end)
1 Like