Skip to content

Instantly share code, notes, and snippets.

@potch
Last active March 16, 2022 13:21
Show Gist options
  • Save potch/8e13aad0b7daa81d423bc8ddec02508a to your computer and use it in GitHub Desktop.
Save potch/8e13aad0b7daa81d423bc8ddec02508a to your computer and use it in GitHub Desktop.
Playdate list item selector that unifies d-pad and crank input
-- listSelector.lua
-- by potch
-- MIT License
-- Playdate item selector that unifies d-pad and crank input
-- useful for menus where you want to allow either crank or arrow input.
-- First argument `count` is the number of items.
-- second argument `options` is a table with the following optional fields:
-- `initSelected`: the position of the item selected at start. default is 0.
-- `crankScale`: # of crank degrees for each item. default is 90.
-- `orientation`: either "horizontal" or "vertical" (default)- chooses which
-- d-pad inputs change the selected item.
-- returns interface with the following methods:
-- `update()`: call this each frame to re-calculate the selected item.
-- `getSelected()`: returns the current selected item. value in the range 0..count-1
-- `setSelected(n)`: sets the current selected item.
function listSelector(count, options)
options = options or {}
local initSelected = options.initSelected or 0
local selected = 0
local crankScale = options.crankScale or 90
local arrowPos = 0
local crankPos = 0
local orientation = options.orientation or "vertical"
if orientation ~= "horizontal" then
orientation = "vertical"
end
local function update()
if orientation == "horizontal" then
if playdate.buttonJustPressed(playdate.kButtonLeft) then
arrowPos = arrowPos - 1
end
if playdate.buttonJustPressed(playdate.kButtonRight) then
arrowPos = arrowPos + 1
end
else
if playdate.buttonJustPressed(playdate.kButtonUp) then
arrowPos = arrowPos - 1
end
if playdate.buttonJustPressed(playdate.kButtonDown) then
arrowPos = arrowPos + 1
end
end
arrowPos = arrowPos % count
crankPos = (crankPos + playdate.getCrankChange()) % 360
selected = math.floor(initSelected + arrowPos + crankPos / crankScale) % count
end
return {
update = update,
getSelected = function() return selected end,
setSelected = function(n)
initSelected = n
crankPos = 0
arrowPos = 0
end
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment