Make bob speed scale with player velocity

I am developing a bobbing system for my game, that scales off of the players speed. The problem is that i dont know what math i should use. I do know that i can increase the speed by doing something with the tick(). I have tried multiplying the tick() with the velocity divided by ten, and the problem with that is that the tick() variable gets extreme differences when accelerating. But otherwise it would work. Simply adding the velocity actually works, but only when accelerating. When going at a constant speed, its slower then when accelerating. Can someone give a suggestion on how i would go about fixing this? Thank you!

Script (without scaling with velocity)

--Variables
local rs = game:GetService("RunService")

local plr = game.Players.LocalPlayer
local physical = game.Workspace[plr.Name]
local camera = workspace.CurrentCamera

--Bob script
rs.RenderStepped:Connect(function(dt)
	local velocity = physical.HumanoidRootPart.AssemblyLinearVelocity.Magnitude
	
	if velocity > 1 then
		local bobx = math.sin(tick())
		local boby = math.abs(math.cos(tick()))
		local bob = Vector3.new(bobx, boby, 0)
		physical.Humanoid.CameraOffset = physical.Humanoid.CameraOffset:Lerp(bob, 0.25)
	end
	end)
1 Like

math.sin(x) x is measured in radians
it means that math.sin(0)math.sin(2 * math.pi) completes a horizontal bobbing cycle
if we input time as seconds, then it takes 2*pi=6.28 secs for a cycle.
math.sin(time / (2 * math.pi)) will takes 1 second for a cycle.
math.sin(speed * time / (2 * math.pi)) will make it faster by speed

while tick() does return a time measured in seconds, it starts at epoch, and multiplying it with a changing speed doesn’t work well.
we should make use of dt and accumulate

local t = 0
rs.RenderStepped:Connect(function(dt)
  local speed = ... -- we usually use 'velocity' for a vector, and 'speed' for its magnitude
  local speedFactor = 1 -- you can adjust this for your need
  t += dt * speed * speedFactor
  ...
  local bobx = math.sin(t / (2 * math.pi))

Thank you so much! Worked very well ^^