Checking if parts are behind another part

Hello, I am trying to have the player highlight when they see a part on their screen but it highlights them even if the part is behind a wall, so far I have tried using Camera:WorldToViewportPoint but it does not check if the part is behind another part.

local Players = game:GetService("Players")

local Camera = workspace.CurrentCamera
local PartChecking = workspace.Part
local IsHighlighted = false
local LocalPlayer = Players.LocalPlayer

while true do
	task.wait()
	local ScreenPosition, OnScreen = Camera:WorldToViewportPoint(PartChecking.Position)
	if OnScreen and not IsHighlighted then
		IsHighlighted = true
		Instance.new("Highlight").Parent = LocalPlayer.Character
	end
end

So does anyone know a way to detect if the part is behind another part?

1 Like

you could cast a raycast from the character to the part and check if there is something hitting between it

Try using this code, let me know how it works out for you.

local RunService = game:GetService("RunService")
local camera = workspace.CurrentCamera
local player = game.Players.LocalPlayer

local targetPart = workspace:WaitForChild("TargetPart") -- The part you are checking
local originPart = camera -- Start the ray from the camera position


local function isPartBehindAnother(part)
	
	local partPosition = part.Position

	
	local rayOrigin = camera.CFrame.Position
	local direction = (partPosition - rayOrigin).Unit * 1000 -- To extend the ray forward
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {camera, player.Character} -- Ignore the camera and player


	local result = workspace:Raycast(rayOrigin, direction, raycastParams)

	-- If the ray hits an object, check if it's the target part
	if result then
		if result.Instance ~= part then
			return true -- It's behind another part
		end
	end

	return false -- Not behind anything
end

-- Continuously check if the part is behind another object
RunService.RenderStepped:Connect(function()
	if isPartBehindAnother(targetPart) then
		print(targetPart.Name .. " is behind another part!")
	else
		print(targetPart.Name .. " is visible!")
	end
end)

Instead of Highlighting, I used rays. If you like highlighting more just change the variables


With viewport frame masking I’m sure you could achieve a very clean look. It would be a massive pain to properly implement this

This code was right what I needed thank you very much for helping me out.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.