How to check if a CFrame is behind the camera?

I thought this would be straightforward, but I have found nothing else like this question on the forum. I have a CFrame which I want to check if is behind my player’s camera. I do not want this to be mixed up with it not being on their screen, I want it to strictly be BEHIND the camera’s position & orientation, preferably with a 180* margin.

Here is an illustration to help elaborate

Raycasts are not a viable option, as the code is running in parralel.
I have tried

local ObjectSpace = bone.WorldCFrame:inverse() *cam.CFrame;
			local MaxDistance = 20;
			local Run = true;
			--
			if ObjectSpace.Z < 0 and (cam.CFrame.p - bone.WorldCFrame.p).magnitude >= MaxDistance then
				Run = false;

			end

But this half worked and would not update when the camera turned around,
Many thanks!

I think something like this would work

-- I'm going to assume the target CFrame is called 'target' and the Camera is 'camera'
local toTarget = (target.Position - camera.CFrame.Position).Unit
local dot = camera.CFrame.LookVector:Dot(toTarget)

if dot < 0 then
    -- target CFrame is behind camera
else
    -- target CFrame is not behind camera
end

If my math is correct, when the dot product is negative that means the two vectors are pointing in the opposite directions and so the target CFrame should be behind camera.

3 Likes

Use the built-in RobloxAPI.

RobloxAPI:IsCFrameBehindCamera(CFrame,Camera)

yes, thats true, i also use the dot product to check if a player is looking at another player, so this is the same concept, but to reach something more like what is described in the picture, i would change the threshold of the

if dot < 0 then

to

if dot < -.2

or something similar to that, you need to play around with the numbers
ive printed these dot products that i use in my game, going all around the back of a character, and these were the results
image
in this example, dot is approximately -0.1 so it would still count (use characters’ head as reference point, which i guess would count as “area not on camera but shouldnt be considered”)
image
(imagine the head of the green dummy as the camera, and mine as the cframe)
if i am wrong, please correct me, and also dont listen to miserable_haven

Ok thanks I will try both these now.

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