I am trying to make a script in which the pet moves behind the player, however when i attempt this it does move behind the player but when the player faces a certain way, the pet moves infront.
Example: https://gyazo.com/48818a064bcb7ee040ab0b7d96742e73
The script i am using to achieve this is:
while wait() do
for i = 0, 1, 0.01 do
local playerpos = script.Parent.Parent:GetPrimaryPartCFrame()
wait()
script.Parent:SetPrimaryPartCFrame(script.Parent.Head.CFrame:lerp((playerpos + Vector3.new(3,1,0)), i))
end
end
local pet = script.Parent
local character = script.Parent.Parent
while wait() do
for i = 0, 1, 0.01 do
wait()
local petCframe = pet.PrimaryPart.CFrame
local characterCframe = character.PrimaryPart.CFrame
local targetCframe = characterCframe:ToWorldSpace(CFrame.new(3,1,0))
local newCframe = petCframe:Lerp(targetCframe, i)
pet:SetPrimaryPartCFrame(newCframe)
end
end
Also, you’d be better off running this type of function on RunService.Heartbeat, instead of using a while+for loop. You might notice choppiness otherwise.
You could use an arbitrary value for the alpha of the Lerp. For example: by using a small value you’ll notice the pet moves slower, but using a value closer to 1 will make it move much faster. This also allows you a greater control over the pet follow speed.
local LERP_ALPHA = .05; -- value between 0 and 1. 1 == instant update, ~0 == slower movement towards the target CFrame.
local pet = script.Parent
local character = script.Parent.Parent
local function Update()
local petCframe = pet.PrimaryPart.CFrame
local characterCframe = character.PrimaryPart.CFrame
local targetCframe = characterCframe:ToWorldSpace(CFrame.new(3,1,0))
local newCframe = petCframe:Lerp(targetCframe, LERP_ALPHA)
pet:SetPrimaryPartCFrame(newCframe)
end
game:GetService("RunService").Heartbeat:Connect(Update)