How can I fix my bobbing script?

Hello, I have been working on a pet that moves on the map and I want to give it a bobbing effect but this happens:


It goes through the ground and if I make the number smaller it goes way too over the ground. How do I add a distance and then remove it to make the pet go to the original place instead of going through the ground?
Here is my code:

local pet = workspace.Pet


game:GetService('RunService').RenderStepped:Connect(function()
	local cf = pet.PrimaryPart.CFrame * CFrame.new(0,0,-1)

	pet:SetPrimaryPartCFrame(pet.PrimaryPart.CFrame:Lerp(cf * CFrame.new(0, 1* math.sin(time() * 20), 0), .1) ) 
end)

Thank you!

I believe you would have to change the original height of the pet.

Right now, you are using a sine function. The β€œ1” you multiplied to the sine function represents the amplitude, or the vertical distance between each trough and crest of the wave. To get the middle ground, you must divide the amplitude by two. Then, you can offset your model vertically by that middle ground.

To modify your code, here’s what I’d do

local pet = workspace.Pet

local AMPLITUDE = 1 -- The number of studs the pet will be bouncing up and down
pet.PrimaryPart.CFrame *= CFrame.new(0, AMPLITUDE/2 , 0) -- Offset the Pet

game:GetService('RunService').Heartbeat:Connect(function()
	local cf = pet.PrimaryPart.CFrame * CFrame.new(0,0,-1)
	pet:SetPrimaryPartCFrame(pet.PrimaryPart.CFrame:Lerp(cf * CFrame.new(0, AMPLITUDE * math.sin(time() * 20), 0), .1) ) 
end)
1 Like

Thank you! It works like a charm!

1 Like