Hello,
I’ve been working on a script that makes NPCs in my game look over towards the player when they are within 15 studs of the player. My problem is that it is really jumpy when the player walks in/out of the 15 stud radius and when the player walks in certain points around the NPC. I am trying to make the NPC transition back to its default state smoothly if the player walks out of the radius, and make it not jump around when I walk around it.
Here is the script that I have currently, I referenced this page while I was making the script.
local NpcFold = workspace["NPC Holder"]
local player = game.Players.LocalPlayer
function limitAngles(CF,X,Y)
X = math.rad(X); Y = math.rad(Y)
local x, y = CF:toEulerAnglesXYZ()
return CFrame.new(CF.p) * CFrame.Angles(
math.clamp(x, 0, X),
math.clamp(y, -Y, Y),
0
)
end
game:GetService("RunService").Stepped:Connect(function()
local NPCs = NpcFold:GetChildren()
if player.Character then
for i,v in pairs(NPCs) do
if v:IsA("Folder") then
local group = v:FindFirstChild(" ")
if group then
local torso = group.HumanoidRootPart
local localTorso = player.Character:FindFirstChild("HumanoidRootPart")
local waist = group.UpperTorso.Waist
local neck = group.Head.Neck
if localTorso then
local char = player.Character
local magnitude = (torso.Position - localTorso.Position).magnitude
if magnitude < 20 then
local RotationOffset = (group.PrimaryPart.CFrame-group.PrimaryPart.CFrame.p):inverse()
local realPos = -(group.PrimaryPart.CFrame.p - char.PrimaryPart.Position).unit *5000
local targetCFrame = RotationOffset * CFrame.new(Vector3.new(0, 0, 0), realPos)
waist.Transform = limitAngles(targetCFrame,0,20)
local RotationOffset = (group.UpperTorso.CFrame-group.UpperTorso.CFrame.p):inverse()
local realPos = -(group.UpperTorso.CFrame.p - char.PrimaryPart.Position).unit *5000
local targetCFrame = RotationOffset * CFrame.new(Vector3.new(0, 0, 0), realPos)
neck.Transform = limitAngles(targetCFrame,30,65)
end
end
end
end
end
end
end)
Here is a video of the problem that I’m having
YouTube Link
As you can see, it’s jumpy looking and doesn’t look that good.
Here is an example of what I’m trying to do, this is from Egg Hunt 2018.
YouTube Link
Any help is appreciated, thanks. Let me know if I need to provide any more information.