Detect when a player looks at part

I’m making a horror-type game, and I want to make it so when a player looks at the entity, it disappears. How would I go about making this?

5 Likes

Use mouse.Target if u want it to disappear if player points at it. Or use game.Workspace.CurrentCamera:WorldToScreenPoint() if you want to get the position of
the instane on the players screen.

Using CurrentCamera:WorldToScreenPoint, how would I know if the player sees the part? Would I do

if game.Workspace.CurrentCamera:WorldToScreenPoint(part) then

?

This will completely give you the solution:

1 Like

Problem is, my game is third person.

This also works in third person

local MainPart = workspace.MainPart
local Camera = game.Workspace.CurrentCamera
local Player = game:GetService("Players").LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()

local Params = RaycastParams.new()
Params.FilterType = Enum.RaycastFilterType.Blacklist
Params.FilterDescendantsInstances = { Character }

local function Visibilty()
	-- Check if the jumpscare object is on the player screen
	local Vector, OnScreen = Camera:WorldToScreenPoint(MainPart.Position)
	
	if not OnScreen then
		return false
	end
	
	-- Cast a ray to the jumpscare object
	
local Result = workspace:Raycast(Camera.CFrame.Position, (MainPart.Position - Camera.CFrame.Position).Unit * 500, Params)
	
	-- Check if the raycast hit anything and if what was hit is the jumpscare object
	if Result and Result.Instance == MainPart then
		return true
	end
end


while true do
	local Visible = Visibilty()
	
	if Visible then
		task.wait(1)
		MainPart:Destroy()  
	end
	
	task.wait(1)
end
4 Likes