Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I fix my NPC to look at the player correctly?

Asked by
5xephos 15
2 years ago

I have a server script in this NPC and its suppose to look at the closest player, the problem is when I rotate the NPC and the player jumps it tilts it's head sideways to the right but tracks the player correctly when just walking around

local function observePlayer()
    local cFrame0 = neck.C0
    while true do
        local player = findClosestPlayer()
        if player then
            local look = dummy.UpperTorso.CFrame.LookVector
            local facingDirection = (player.HumanoidRootPart.Position - dummy.Head.Position).Unit
            local dot = look:Dot(facingDirection)
            local angle = math.deg(math.acos(dot))

            local isNotAbove = dummy.PrimaryPart.CFrame:ToObjectSpace(player.PrimaryPart.CFrame).Y < 2
            -- can be used to detect if dummy is above

            local isInFront = dummy.PrimaryPart.CFrame:ToObjectSpace(player.PrimaryPart.CFrame).Z < 0       
            if isInFront and angle <= 60 then
                local unit = -(dummy.PrimaryPart.CFrame.p - player.PrimaryPart.Position).unit 
                neck.C0 = cFrame0 * CFrame.new(Vector3.new(0,0,0), unit) * CFrame.Angles(math.rad(dummy.PrimaryPart.Orientation.X), -math.rad(dummy.PrimaryPart.Orientation.Y), 0)
            end
        end
        wait()
    end
end

Answer this question