Better way to make a pet following system without lag?

I want to make a pet system without lagging up the game like crazy. I know using a constantly running loop makes the game lag, so I thought of a way to make the pet only follow the player when the player is walking. This is basically what it looks like:

local Walking = false 

Player.Humanoid.StateChanged:Connect(function(Old, New)
if New == Enum.HumanoidStateType.Running then
Walking = true
Walking = false

while Walking == true do
-- Change the BodyPosition and bodygyro 

I’m on mobile right now and can’t test it, but if this works then it might help a little bit. Still, most of the time people are walking around and the while loop will be running, so this system isn’t good for stopping lag. What I really want is a pet system without a ton of while loops.


The best way to do it is a .Changed or GetPropertyChanged event when the player’s position changes, the pet updates to its position accordingly. This way the code only runs when necessary instead of in a constant while loop. Good luck!

Then when done, you can disconnect the function and it will get garbage collected.

func = Player.Head:GetPropertyChangedSignal("Position"):Connect(function()
local newpos = Player.Head.Position
--Code Here

end) --End of Humanoid State Changed

Perhaps just use a WeldConstraint to keep the pet locked onto the player?

1 Like

This won’t look as realistic unfortunately, as it wont have any freedom to change relative position to the player. Additionally, you would still have to compute orientation of the animal and do animations and such, so it isn’t really beneficial considering you lose out on certain freedoms that you get with doing vector/cframe calculations to determine where the pet moves.

I told it to print something whenever it fired, and it only did once. I don’t think Changed or GetPropertyChangedSignal works with position.

I don’t see why you can’t just have a local script that renders the pets. That way you can easily add an option to just not render other people’s pets. Update all the pets in the same loop on a 0.03 wait suppose you could also add a cframe object to the player in the local script and compare the old cframe to the new one. If the player is in the same cframe don’t update. Also wouldn’t using changed or getpropertychangedsignal fire thousands of times a second? ( Barely use these two like this )

I would do that, but a feature in my game is that people’s pets can attack other people, so they need to see all the pets in the game. And that might be why :GetPropertyChangedSignal doesn’t work with position, it fires too often.

Then just don’t have a option to turn them off?

But then we get the same problem, everyone has to see the pets move and it lags.

That’s a good idea though, instead of a ton of while loops I’ll make one that moves all the pets to their owners.