How can I make an object disappear on sight?

Hello everyone, I’ve been working on a little horror game project and I’m trying to make a monster disappear once it is in the view of the camera, but I’m not sure how to track what is being seen. Does anyone know how to make this, or know any pages that can help me out with this?

This is inspired by the red eyed monster “Stan” from Isle where if you wander into his zone, he stalks you and if you happen to see him, he disappears.

4 Likes

Anything that falls within the “pyramid of vision” of the camera is visible.

ViewFrustum.svg.png

Start with a function that determines whether a point is within this pyramid.

The easiest way to do that is to transform the position of the point such that the “origin” is the camera’s CFrame, not (0, 0, 0) of the world, or to make it relative to the camera. So that a transformed position of (0, 0, 10) really is exactly 10 studs in front of the camera
CFrame:PointToObjectSpace(Vector3) does exactly this.

Then you can use trigonometry to check the angle that the x coordinate and z coordinate would form, and compare it to the horizontal field of view.
Same with y and vertical field of view.
Also check that the z coordinate is positive, that the point is not behind the camera.

local camera = workspace.CurrentCamera -- must be in a LocalScript

function isPositionVisible(pos)
	local relative = camera:PointToObjectSpace(pos)
	
	-- not behind the camera
	if relative.Z < 0 then return false end
	
	-- horizontal field of view isn't directly provided to us, but we do get diagonal field of view
	-- (and screen size in pixels, too, that's another way to find the horizontal fov)
	local fovHorizontal = math.sqrt(camera.DiagonalFieldOfView ^ 2 - camera.FieldOfView ^ 2)
	
	if math.deg(math.atan2(relative.X, relative.Z)) * 2 > fovHorizontal) -- the 2 is necessary because the fov is centered on the forward direction and so can go 0-180°. but atan2 only outputs 0-90°
	or math.deg(math.atan2(relative.Y, relative.Z)) * 2 > camera.FieldOfView)
	then return false end
	
	return true
end

Now you can check whether the object or any of the 6 corners of it are visible, then make it disappear shortly after.

Be warned that players can shrink the screen vertically to get a crazy horizontal field of view. (Though a horror game player wouldn’t really do that)
It also doesn’t account for fog (long distances)

10 Likes

Thank you so much!

(abcdefghi)

2 Likes