Hello, I have been working on a pet folliwing system but I am struggling to make the pet always face behind the player.
Here is my code:
local pet = workspace.Pet
local character = script.Parent
game:GetService("RunService").RenderStepped:Connect(function()
local rayOrigin = Vector3.new(pet.PrimaryPart.Position.X, pet.PrimaryPart.Position.Y + 20 , pet.PrimaryPart.Position.Z)
local params = RaycastParams.new()
params.FilterDescendantsInstances = {pet}
params.FilterType = Enum.RaycastFilterType.Blacklist
local direction = Vector3.new(0, -1, 0)*100
local ray = workspace:Raycast(rayOrigin, direction, params)
if ray then
pet:SetPrimaryPartCFrame(CFrame.new(character.PrimaryPart.CFrame.X + 5,ray.Position.Y+ pet.PrimaryPart.Size.Y/2,character.PrimaryPart.CFrame.Z+5))
end
end)
In this case you’re gonna use goniometrics functions sin and cos.
Find player’s yaw angle (Y rotation coordinate)
Transform the angle into radians using math.rad(angle)
Calculate new pet’s position using math.sin and math.cos
local position = Vector3(
playerPosition.X + math.cos(rad) * 5.0,
playerPosition.Y,
playerPosition.Z + math.sin(rad) * 5.0,
)
I recommended experimenting with this. This code will bring your pet in front of your player, if you wanna put your pet behind yourself, you must increment the angle by 180.
It’s also important to mention that this solution can move your pet only on a circle of specific size (which is 5).
Circle image should help you understand the angles, to position your pet correctly. Cosinus is more horizontally bound where 0° is 1 and 180° is -1, however Sinus is vertically bound where 90° is 1 and 270° is -1. Where cosinus is always 1 or -1, there is sinus always 0 and vice-versa.