Making the pet move BEHIND the player at all times

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:

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
1 Like

Try using local space of the head’s CFrame when doing this.

local newCframe = headCFrame:ToWorldSpace(CFrame.new(3,1,0))

How would i incorporate this into the script? this is the first time i see “:ToWorldSpace()”

You could try something like this:

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.

6 Likes

It works great, and how exactly would i switch out the for loop with a RunService.Heartbeat as i would need the “I” value when lerping

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)
4 Likes

Ahh okay now that makes sense, thank you so much for the help i appreciate it ! :slight_smile:

1 Like