Skip to content

Instantly share code, notes, and snippets.

@EntranceJew
Last active December 9, 2019 11:24
Show Gist options
  • Save EntranceJew/eb05ff34f551925121bc to your computer and use it in GitHub Desktop.
Save EntranceJew/eb05ff34f551925121bc to your computer and use it in GitHub Desktop.
Generating control handlers from a configuration table.using the tactile library in love2d. Whether or not you use the component-system separation is up to you!
-- inside Player:initialize()
local Player = class("Player")
Player:initialize()
--snip
self.keybinds = {
moveHorizontal = {
majorType = "Axis",
config = {
{
type = "binaryAxis",
vals = {'a', 'd'},
},
{
type = "analogStick",
vals = {'leftx', 1}
},
}
},
moveVertical = {
majorType = "Axis",
config = {
{
type = "binaryAxis",
vals = {'w', 's'},
},
{
type = "analogStick",
vals = {'lefty', 1}
},
}
},
jump = {
majorType = "Button",
config = {
{
type = "key",
vals = {'w'},
},
{
type = "key",
vals = {'space'},
},
{
type = "gamepadButton",
vals = {'a', 1}
},
}
},
}
end
return Player
local PlayerControlSystem = tiny.processingSystem(class "PlayerControlSystem")
PlayerControlSystem.filter = tiny.requireAll("controlable", "keybinds")
function PlayerControlSystem:process(e, dt)
-- mandatory fun
e:tactileUpdate(dt)
-- this is excluding any processing of controls that the entites themselves do
end
-- only update buttons
local function tactileUpdate(self, dt)
for _, button in pairs(self.buttons) do
button:update(dt)
end
end
-- relies on lume for shallow table copying
function PlayerControlSystem:onAdd(e)
local kb = e.keybinds
e.controls = {}
e.buttons = {}
for bindName, bindDef in pairs(kb) do
local pool = {}
for bindIndex, bindConfig in pairs(bindDef.config) do
local vals = lume.clone(bindConfig.vals)
-- special exception because they use sub-types and such
if bindConfig.type == "binaryAxis" then
vals[1] = tactile.key(bindConfig.vals[1])
vals[2] = tactile.key(bindConfig.vals[2])
elseif bindConfig.type == "thresholdButton" then
vals[1] = tactile.analogStick(unpack(bindConfig.vals[1]))
end
-- dynamically create the list of possible binds per category
local metacontrol = tactile[bindConfig.type](unpack(vals))
table.insert(pool, metacontrol)
end
-- dynamically create the control type from the established pool
local control = tactile['new' .. bindDef.majorType](unpack(pool))
e.controls[bindName] = control
if bindDef.majorType == "Button" then
e.buttons[bindName] = e.controls[bindName]
end
end
e.tactileUpdate = tactileUpdate
end
return PlayerControlSystem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment