Detect if player looks at part

Do you want to know if a player is directly looking at a part or if it is simply on the screen? If you want the former, raycasting is probably your best bet. You can roughly implement it like this:

local part = workspace:WaitForChild'a part'; --a part to determine whether the player is looking at
local cam = workspace.CurrentCamera;
local length = 100; --a max distance in which the ray can detect objects. we multiply the camera's look vector by this number
local cfg = RaycastParams.new();
cfg.FilterDescendantsInstances = {game.Players.LocalPlayer.Character}; --specify a table of anything that the raycast should ignore (you always stare at your character, so i highly recommend you keep the player's character in here)
	
local cast = workspace:Raycast(cam.CFrame.Position, cam.CFrame.LookVector * length, cfg); --start a ray at the camera's position and extrude it in its look direction (cframe allows you to determine both position and orientation of the camera) with our specified ray parameters
	
if cast and cast.Instance == part then --make sure the ray actually hit something and make sure its the part we want to know about
	--do stuff
end

Otherwise, detecting whether an object is on the screen is even simpler:

local part = workspace:WaitForChild'whatever';
local cam = workspace.CurrentCamera;

local isOnScreen = select(2, cam:WorldToViewportPoint(part.Position)); --get the position of the object in question on the player's screen. this also tells you whether the passed in vector is actually on the player's visible viewport or not, which is the only thing we need (hence select)
30 Likes