Skip to content

Instantly share code, notes, and snippets.

@amacdougall
Created September 11, 2021 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amacdougall/a1c977e2036d529bbdb76109cffdb3ea to your computer and use it in GitHub Desktop.
Save amacdougall/a1c977e2036d529bbdb76109cffdb3ea to your computer and use it in GitHub Desktop.
Simple beat sync mechanism for PICO-8
sync = (function()
local speed = 16 -- can be hardcoded for this project
local prev_elapsed = 0 -- ticks elapsed in current note
function execute(f) f() end
local callbacks = {
[32] = {}, [16] = {}, [8] = {}, [4] = {}, [2] = {}, [1] = {}
}
return {
on = function(note_length, f)
add(callbacks[note_length], f)
end,
off = function(note_length, f)
del(callbacks[note_length], f)
end,
update = function()
tick = stat(26)
elapsed = tick % speed
if elapsed < prev_elapsed then
-- new beat has begun
beats = flr(tick / speed)
foreach(callbacks[32], execute)
if (beats % 2 == 0) foreach(callbacks[16], execute)
if (beats % 4 == 0) foreach(callbacks[8], execute)
if (beats % 8 == 0) foreach(callbacks[4], execute)
if (beats % 16 == 0) foreach(callbacks[2], execute)
if (beats % 32 == 0) foreach(callbacks[1], execute)
end
prev_elapsed = elapsed
end
}
end)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment