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?
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