I want to make a script that makes the player’s character’s or even an NPC’s head look at certain objects in the workspace, sort of like how in games outside of roblox, the character’s head turns to face key items or other npcs. Ive seen code such as:
local neck = script.Parent.Torso["Neck"]
local NPC = script.Parent
function getClosestPlayer()
local closest_player, closest_distance = nil, math.huge
for i, player in pairs(workspace:GetChildren()) do
if player:FindFirstChild("Humanoid") and player ~= NPC then
local distance = (NPC.PrimaryPart.Position - player.PrimaryPart.Position).Magnitude
if distance < closest_distance then
closest_player = player
closest_distance = distance
end
end
end
return closest_player
end
local cframe0 = neck.C0
while true do
local player = getClosestPlayer()
if player then
local is_in_front = NPC.PrimaryPart.CFrame:ToObjectSpace(player:FindFirstChild("HumanoidRootPart").CFrame).Z < 0
if is_in_front then
local unit = -(NPC.PrimaryPart.CFrame.p - player.PrimaryPart.Position).unit
neck.C0 = cframe0 * CFrame.new(Vector3.new(0, 0, 0), unit) * CFrame.Angles(90, -math.rad(NPC.PrimaryPart.Orientation.Y), 0)
end
end
wait()
end
The issue with this is that with r6 models, the head kinda “breaks” as shown below
What Im trying to achieve: