How would i check if an object is offscreen?

so i have this local script here for a simple project i’m working on, but i’m not sure how to go about making it so that i can detect whether or not an object is onscreen or not.

repeat
	task.wait()
until game:IsLoaded()

local player = game:GetService("Players").LocalPlayer
local camera = workspace.CurrentCamera
local viewportX, viewportY = camera.ViewportSize.X, camera.ViewportSize.Y

camera.CameraType = Enum.CameraType.Scriptable

game:GetService("RunService").RenderStepped:Connect(function()
	local part = workspace:FindFirstChild("Part")

	if part then
		camera.CFrame = part.CFrame
	end
end)
1 Like

didn’t work

repeat
	task.wait()
until game:IsLoaded()

local player = game:GetService("Players").LocalPlayer
local camera = workspace.CurrentCamera
local character = player.CharacterAdded:Wait()

camera.CameraType = Enum.CameraType.Scriptable

game:GetService("RunService").RenderStepped:Connect(function()
	local part = workspace:FindFirstChild("Part")
	local _, onScreen = camera:WorldToScreenPoint(character.PrimaryPart.Position)
	
	if onScreen then
		if #camera:GetPartsObscuringTarget({camera.CFrame.Position, character.PrimaryPart.Position},{workspace:WaitForChild("Baseplate")}) == 0 then
			print("onscreen") -- never prints
		end
	end

	if part then
		camera.CFrame = part.CFrame
	end
end)

i did end up solving it myself, thank you for leading me in the right direction with GetPartsObscuringTarget()

repeat
	task.wait()
until game:IsLoaded()

local player = game:GetService("Players").LocalPlayer
local camera = workspace.CurrentCamera
local character = player.CharacterAdded:Wait()

camera.CameraType = Enum.CameraType.Scriptable

game:GetService("RunService").RenderStepped:Connect(function()
	local part = workspace:FindFirstChild("Part")

	if character and part then
		camera.CFrame = part.CFrame
		local primaryPartPosition = character.PrimaryPart.Position

		-- check if the primary part is on screen
		local _, onScreen = camera:WorldToScreenPoint(primaryPartPosition)

		if onScreen then
			local obstructingParts = camera:GetPartsObscuringTarget({camera.CFrame.Position, primaryPartPosition}, {part})
			if #obstructingParts == 0 then
				print("primary part is on screen!")
			else
				print("primary part is on screen but obstructed by other parts.")
			end
		else
			print("primary part is offscreen.")
		end
	end
end)
1 Like

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