Log in to vote

How can I check which direction the camera is facing relative to the humanoid root part?

Asked by 7 months ago

I'm making a cover system and I want to make it so that if the camera is facing behind the humanoid root part then when the player aims, it will stop the crouching animation and have the camera stand up to look over the cover. I searched my question up and found a post. I tried the code but I seemed to only update when I move the character (and not when I turn the camera).


    local angle = math.acos(

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


And sometimes it gets backwards and forwards mixed up depending on which direction the character is facing relative to world space. Any help is appreciated.

1 answer

Log in to vote
Answered by
TGazza 834 Moderation Voter
7 months ago

Everything seems to be working. Might be something else causing the problems.

I've re-wrote the above code so its a little bit more readable:

local RunService = game:GetService("RunService")
local Player = game.Players.LocalPlayer

local character = Player.Character ~= nil and Player.Character or Player.CharacterAdded:wait()
local HRP = (character ~= nil and character:WaitForChild("HumanoidRootPart",10) ~= nil) and character.HumanoidRootPart or nil
local camera = workspace.CurrentCamera


    local Dir = camera.CFrame.LookVector:Dot(HRP.CFrame.LookVector)
    local angle = math.acos(Dir)*180/math.pi --// don't need to clamp this! as it allready returns a value between -1 and 1 THEN times by 180 and divided by pi to get a value in deg

    local isBackwards = false
    if angle > 90 then
        isBackwards = true

I ran the above code from a local script inside the playerscripts folder then started the game and moved the camera. No matter where i place the camera the script works and flips the backwards value when looking behind my character.

Could it be your animation making the code think your looking behind by turning your HumanoidrootPart 180 without turning the rest of your character?.

Just my thoughts!


Answer this question