I have an NPC that is supposed to teleport slowly towards the nearest player with a distance limit, the full script here:
local evil = script.Parent
local humanoid = evil:WaitForChild("Humanoid")
local hitbox = evil.NotTorso
local snd = hitbox:WaitForChild("teleport")
function FindTarget()
local maxDistance = math.huge
local target = nil
for i,v in pairs(workspace:GetChildren()) do
if v:FindFirstChild("Humanoid") then
if (v.Humanoid.RootPart.Position-evil.Humanoid.RootPart.Position).magnitude < maxDistance then
target = v.Humanoid.RootPart
end
end
end
return target
end
task.defer(function()
while task.wait(40 / (humanoid.WalkSpeed)) do
local maxDistance = humanoid.WalkSpeed * 2.5
local target = FindTarget()
print(target, target.Position)
if not target then return end
local position = target.Position
local direction = (humanoid.RootPart.Position - position).Unit
local distance = (humanoid.RootPart.Position - position).Magnitude
if distance > maxDistance then
distance = maxDistance
end
local targetPos = (humanoid.RootPart.Position + direction * -distance)
local RX, RY, RZ = CFrame.lookAt(humanoid.RootPart.Position, targetPos):ToOrientation()
local lookAt = CFrame.Angles(0,RY,0)
local targetCF = CFrame.new(targetPos) * lookAt.Rotation
evil:PivotTo(targetCF)
humanoid.Sit = false
end
end)
For some reason, when the npc gets to the same position as the nearest player, it teleports to ~ (0,90000,0) and slowly teleports back down or gets destroyed.
rarely, it also disappears upon spawning to the same position.
i have narrowed the issue down to this part. it is supposed to get the orientation for the NPC to point towards the player.
local RX, RY, RZ = CFrame.lookAt(humanoid.RootPart.Position, targetPos):ToOrientation()
local lookAt = CFrame.Angles(0,RY,0)
local targetCF = CFrame.new(targetPos) * lookAt.Rotation
what should i do about this issue?