Detecting if camera is facing toward front of character

I’m making some weapons. And I’m trying to figure out how to detect if the player’s camera is facing towards the front of their character. I don’t know if this is possible but if you have any tips on how to achieve this please let me know.

Here’s my code for moving the waist to face the camera direction.

--Set rotated start cframe inside head
local startCFrame = CFrame.new((hrp.CFrame.p + Vector3.new(0,2,0)))*CFrame.Angles(0, math.rad(xAngle), 0)*CFrame.Angles(math.rad(yAngle), 0, 0)
					
--Set camera focus and cframe
local cameraCFrame = startCFrame + startCFrame:vectorToWorldSpace(Vector3.new(cameraPos.X,cameraPos.Y,cameraPos.Z))
local cameraFocus = startCFrame + startCFrame:vectorToWorldSpace(Vector3.new(cameraPos.X,cameraPos.Y,-50000))
camera.CFrame = CFrame.new(cameraCFrame.p,cameraFocus.p)
local space = CFtoObjectSpace(hrp.CFrame, camera.CFrame).lookVector.unit --hrp.CFrame:toObjectSpace(mouse.Hit).lookVector.unit
local space_x = space.X
local space_z = space.Z
local space_y = space.Y
local asx_torso = -math.asin(space_x)
local asy_torso = math.asin(space_y)
local asz_torso = math.clamp(math.asin(space_z),MIN_TORSO_ROTATE_Z,MAX_TORSO_ROTATE_Z)

--detection

if backwards == true then 
	if asx_torso > 0 and asx_torso < 1.57 then
		asx_torso = asx_torso + ( -1.57 )  * -2
	elseif asx_torso < 0 and asx_torso > -1.57 then
		asx_torso = asx_torso + ( 1.57 )  * -2
	end
end
waist.C0 = CFrame.new(WAIST_X,WAIST_Y,0)*CFrame.Angles(0,-asx_torso,0)*CFrame.Angles(asy_torso,0,0)--*CFrame.Angles(-math.pi-asy_torso,0,math.pi)--*CFrame.Angles(0,0,asz_torso)
WaistRotation_Event:FireServer(waist.C0)
1 Like

I think the easiest way would be comparing look vectors between the camera and the HRP. You can just use the dot product to compare it:

local HRP = -- humanoid root part

local angle = math.acos(
    math.clamp(
        camera.CFrame.LookVector:Dot(HRP.CFrame.LookVector),
    -1, 1)
)

local backwards = false
if angle > math.pi/2 then
	backwards = true
end
7 Likes

:heart_eyes: Thanks. Works perfectly now!

1 Like

BTW, dot product should always be between [-1, 1] for unit vectors, but floating point errors can occur and cause it to go out of range. This makes acos fail, so I always clamp dot products between [-1, 1] before using acos.

3 Likes