Sync footstep sounds with math?

Hey, I am trying to sync footstep sounds with math, but my abilities are not good as math is not my highest skill so, I am asking the dev community. The only issue here is that the sounds are out of sync by a about .25 seconds or so, even more while going slower.

Here is a gif of the out-of-sync footsteps: https://streamable.com/xq55g

Here is my current progress:

Note: all of this code is on the client

Code
local cur_ws = humanoid.WalkSpeed
local studs = 3.5 + (move_delta.magnitude / .65)
local foot_delta = studs / root.Velocity.magnitude

if move_delta.magnitude > 0 then
	local down_ray = Ray.new(root.Position, Vector3.new(0, -root.Size.Y / .5, 0))
	local hit, pos = workspace:FindPartOnRayWithIgnoreList(down_ray, {char})
	
	if hit and tick() - last_move_delta >= foot_delta then
		
		local category = fss:FindFirstChild(get_fss():lower())
		
		if category then
			local sound = category:GetChildren()[math.random(1, #category:GetChildren())]

			self.stepped = not self.stepped do
				int_event:FireServer(
					'replicate', 
					'sound', 
					not self.stepped and char.LeftFoot or char.RightFoot,
					sound.SoundId,
					sound.PlaybackSpeed
				)
			end
		end
		
		last_move_delta = tick()
	end
end
last_move_pos = root.Position

any and all help is greatly appreciated and would help me on my journey to create an epic game.

Alternative


You can choose to sync the steps with the animations by picking out the keyframe out of the animation that is loaded.

This is done by the following sources.

Sources:
https://developer.roblox.com/api-reference/class/Keyframe
https://developer.roblox.com/api-reference/function/Keyframe/AddMarker
https://developer.roblox.com/api-reference/function/AnimationTrack/GetMarkerReachedSignal
The link above had a sample of footstep code:

local player = game.Players:GetChildren()[1]
local character = game.Workspace:WaitForChild(player.Name)
local humanoid = character:WaitForChild("Humanoid")
 
local anim = Instance.new("Animation")
anim.AnimationId = "rbxassetid://437855404"
local animTrack = humanoid:LoadAnimation(anim)
 
animTrack:GetKeyframeReachedSignal("FootStep"):Connect(function(value)
    print(value)
end)
animTrack:Play()
2 Likes

That doesn’t seem to work as the method ‘GetKeyframeReachedSignal’ is not a valid member of the AnimationTrack, thanks for your help anyways.

Does using GetMarkerReachedSignal work?

Yep, not sure why keyframe didn’t work, but thanks.