Hello Devs,
I have this Mob that is suppose to look at the player but when the mob looks at the player it does not look at the player smoothly any help here is the video footage. Plus I need help to get the position of the Torso while the player is moving because the player needs to jump for it to detect.
here is the script
local Head = script.Parent
local LookWait = 0
local Distance = 100
while wait(LookWait) do
local target = nil
for i,v in pairs(game.Workspace:GetChildren()) do
local Human = v:FindFirstChild("Humanoid")
local Torso = v:FindFirstChild("Torso") or v:FindFirstChild("HumanoidRootPart")
if Human and Torso and Human.Health > 0 then
if (Torso.Position - Head.Position).magnitude < Distance then
local HeadRay = Ray.new(Head.Position, (Torso.Position - Head.Position).Unit * Distance)
local hit, position = game.Workspace:FindPartOnRayWithIgnoreList(HeadRay, {Head})
if hit == Torso then
target = Torso
end
end
end
end
if target then
local Torso = target
Head.CFrame = CFrame.new(Head.Position, Torso.Position)
end
end
Ignore the health I am going to use it so the mob can deal damage.
Any help is appreciated.
That’s happening because the raycast might not be always finding the player to look at, I recommend using tweening because without tween it’ll snap the head to the current position of the player, with tweening it’ll tween there thus looking somewhat ‘smoother’ than snapping.
I recommend not looping ray/search once the ‘target’ is found, what you can do is after finding an target and making sure that target is still in-sight never look for another target and instead focus on that, else once the target isn’t “Seen” anymore you can make it search again.
PS: What I recommended was probably not within your scope which is getting the nearest target so just ignore it.
local ts = game:GetService("TweenService")
local obj = script.Parent
local twi = TweenInfo.new(
.5,
Enum.EasingStyle.Linear,
Enum.EasingDirection.In,
0,
false,
0
)
game.Players.PlayerAdded:Connect(function(plr)
task.wait(3)
while true do task.wait(.1)
local lat = {CFrame = CFrame.lookAt(obj.Position, plr.Character.HumanoidRootPart.Position)}
ts:Create(obj, twi, lat):Play()
end
end)
local Head = script.Parent
local Distance = 100
game:GetService("RunService").Stepped:Connect(function()
local target = nil
for i,v in pairs(game:GetService("Players"):GetChildren()) do
local Char = v.Character
if Char and Char:FindFirstChild("Head") and Char:FindFirstChild("Humanoid") and Char:FindFirstChild("Humanoid").Health > 0 then
if (Char.PrimaryPart.Position-Head.Position).Magnitude < Distance then
local LookVec = Head.CFrame.LookVector.Unit
local Pos = Char:FindFirstChild("Head").Position
local Pos2 = Head.Position
local Pos3 = (Pos-Pos2).Unit
local DotProduct = LookVec:Dot(Pos3)
if DotProduct > 0.5 then
target = Char.HumanoidRootPart
end
end
end
end
if target then
local Torso = target
Head.CFrame = CFrame.new(Head.Position, Torso.Position)
end
end)