Pet following problem

Hello, I have been working on a pet following system but I am experiencing an issue where when I make the pet follow the player this happens:
It works when I am not stepping on the stairs


But this happens when I am stepping on the stairs:

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

		pet:SetPrimaryPartCFrame(character.PrimaryPart.CFrame * CFrame.new(5,(ray.Position.Y+ pet.PrimaryPart.Size.Y/2 ) -3,5))
	end
end)

How can I fix this?
Thank you!

I’m not sure if it will fix this, but you should also check whether there was a part found by the ray.

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 and ray.Instance then
		--pet:SetPrimaryPartCFrame(CFrame.new(character.PrimaryPart.CFrame.X + 5,ray.Position.Y+ pet.PrimaryPart.Size.Y/2,character.PrimaryPart.CFrame.Z+5))

		pet:SetPrimaryPartCFrame(character.PrimaryPart.CFrame * CFrame.new(5,(ray.Position.Y+ pet.PrimaryPart.Size.Y/2 ) -3,5))
	end
end)