I’m trying to make a script that detects if the player is looking at a part within certain angles.
Detecting if an object is in front or if the player isn’t looking at it works except when the player is actually visually seeing the part it doesn’t seem to think so, how would I fix this but also take the object blocking view of the parts size into consideration?
local targetPart = script.Parent
local function isObjectBlocking(player)
local head = player.Character and player.Character:FindFirstChild("Head")
if not head then
return false
end
local ray = Ray.new(
head.Position,
(targetPart.Position - head.Position).unit * (targetPart.Position - head.Position).magnitude
)
local hit, _ = workspace:FindPartOnRay(ray, player.Character)
return hit and hit ~= targetPart
end
local function checkHeadDirection()
for _, player in pairs(game.Players:GetPlayers()) do
local character = player.Character
if character and character:FindFirstChild("Humanoid") then
local humanoid = character.Humanoid
local head = character:FindFirstChild("Head")
if head then
local lookVector = (targetPart.Position - head.Position).unit
local partNormal = targetPart.CFrame:pointToWorldSpace(Vector3.new(0, 0, -1)) - targetPart.Position
partNormal = partNormal.unit
local dotProduct = lookVector:Dot(partNormal)
if dotProduct > 0.8 then
if isObjectBlocking(player) then
print(player.Name .. " is looking but object blocked")
else
print(player.Name .. " is looking")
end
else
print(player.Name .. " is looking away")
end
end
end
end
end
local RunService = game:GetService("RunService")
RunService.Heartbeat:Connect(function()
checkHeadDirection()
end)