Recently I have been making a game and would like to add a pet system to it. These pets would follow the user around. Systems like this have already been implemented in other games, but I would like to try and make one myself.
What I am wondering is what is the best way to go around making the pets follow the player. I am not asking for scripts just general advice on a way to do this in a smooth un laggy manner.
I have looked at tutorials online but most seem to be over a year old, so thought I would come here and ask for current advice on the matter.
local event = workspace.p:WaitForChild("event")
local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
game:GetService("RunService").RenderStepped:Connect(function()
event:FireServer(char.Head.CFrame - (char.Head.CFrame.RightVector - Vector3.new(5, 5, 5)))
--assuming you already set the pet to the player
end)
This is code for one pet, it works pretty good and it’s simple.
Creating tweens is okay performance-wise, remote events being rapid fired could possibly break it, but this is unsure since I have tried it in studio before sending.
I’ve found two good options: CFrames and constraints.
One way is to just set the pet’s CFrame every RenderStep
(this would be done client-side)
local function SetPetCFrame()
Pet.CFrame = Hroot.CFrame * CFrame.new(2, 2, -3)
end -- Hroot is player's HumanoidRootPart
game:GetService("RunService"):BindToRenderStep("SetPet", Enum.RenderPriority.Last, SetPetCFrame)
Another way would be to use constraints. The ones I’d normally choose would be AlignPosition and AlignOrientation
(this one would be done server-side instead)
local function AddPetConstraints(Pet, Hroot)
local Att1 = Instance.new("Attachment", Hroot)
local Att0 = Instance.new("Attachment", Pet)
Att1.Position = Vector3.new(2, 2, 3)
local APos = Instance.new("AlignPosition", Pet)
local AOri = Instance.new("AlignOrientation", Pet)
APos.Attachment0 = Att0
APos.Attachment1 = Att1
APos.RigidityEnabled = true
AOri.Attachment0 = Att0
AOri.Attachment1 = Att1
AOri.RigidityEnabled = true
end
Chances are that you don’t have them set up correctly if this is what happens. Consider collisions, network ownership, client rendering and the like first.
Constraints aren’t buggy. This is the nature of the physics engine you’re experiencing.