local TweenService = game:GetService("TweenService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local Character = script.Parent
local HumRootPart = Character.HumanoidRootPart
local function findTarget()
local players = Players:GetPlayers()
local maxDistance = math.huge
local nearestTarget
for _,Player: Player in pairs(players) do
if Player.Character then
local target = Player.Character
local Hum = target:FindFirstChild("Humanoid")
if not Hum or Hum.Health == 0 then continue end
local distance = (HumRootPart.Position - target.HumanoidRootPart.Position).Magnitude
if distance < maxDistance then
nearestTarget = target
maxDistance = distance
end
end
end
return nearestTarget
end
function CFrameToOrientation(cf)
local rx, ry, rz = cf:ToOrientation()
return Vector3.new(math.deg(rx), math.deg(ry), math.deg(rz))
end
local Tween: Tween
local function lookAtPlayer(target)
local Goal = CFrame.lookAt(HumRootPart.Position, target.HumanoidRootPart.Position * Vector3.new(1, 0, 1) + HumRootPart.Position * Vector3.new(0, 1, 0))
Goal = CFrameToOrientation(Goal)
Tween = TweenService:Create(HumRootPart, TweenInfo.new(1,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),{Orientation=Goal})
Tween:Play()
end
local function Loop()
local target = findTarget()
if target then
lookAtPlayer(target)
end
end
RunService.Heartbeat:Connect(Loop)
The same problems occur when used in CFrame.lookAt, what does it matter if using CFrame.Angles? won’t the same thing happen? and I didn’t understand how to use it with CFrame.lookAt
I personally wouldn’t use TweenService as it just reset the orientation back when turning too much. This is what i came up with but you can always change things if you’d like. Replace your lookAtPlayer function with the following.
local function lookAtPlayer(target)
target:SetPrimaryPartCFrame(CFrame.lookAt(
target.HumanoidRootPart.Position,
HumRootPart.Position * Vector3.new(1, 0, 1)
+ target.HumanoidRootPart.Position * Vector3.new(0, 1, 0)
))
end