controls/init.lua

66 lines
1.9 KiB
Lua
Raw Normal View History

2023-12-03 20:44:29 +01:00
controls = {
2023-12-04 09:23:45 +01:00
registered_on_press = {},
registered_on_hold = {},
registered_on_release = {},
players = {},
2023-12-03 20:44:29 +01:00
}
function controls.register_on_press(callback)
2023-12-04 09:23:45 +01:00
table.insert(controls.registered_on_press, callback)
2023-12-03 20:44:29 +01:00
end
function controls.register_on_hold(callback)
2023-12-04 09:23:45 +01:00
table.insert(controls.registered_on_hold, callback)
2023-12-03 20:44:29 +01:00
end
function controls.register_on_release(callback)
2023-12-04 09:23:45 +01:00
table.insert(controls.registered_on_release, callback)
2023-12-03 20:44:29 +01:00
end
2023-12-04 09:00:10 +01:00
minetest.register_on_joinplayer(function(player)
2023-12-04 09:23:45 +01:00
local name = player:get_player_name()
controls.players[name] = {}
for key in pairs(player:get_player_control()) do
controls.players[name][key] = {false}
end
2023-12-03 21:03:02 +01:00
end)
2023-12-04 09:00:10 +01:00
minetest.register_on_leaveplayer(function(player)
2023-12-04 09:23:45 +01:00
local name = player:get_player_name()
controls.players[name] = nil
end)
2023-12-04 09:00:10 +01:00
local function update_player_controls(player, player_controls)
local time_now = minetest.get_us_time()
for key, pressed in pairs(player:get_player_control()) do
if pressed and not player_controls[key][1] then
for _, callback in pairs(controls.registered_on_press) do
callback(player, key)
end
player_controls[key] = {true, time_now}
elseif pressed and player_controls[key][1] then
for _, callback in pairs(controls.registered_on_hold) do
callback(player, key, (time_now - player_controls[key][2]) / 1e6)
end
elseif not pressed and player_controls[key][1] then
for _, callback in pairs(controls.registered_on_release) do
callback(player, key, (time_now - player_controls[key][2]) / 1e6)
end
player_controls[key] = {false}
end
end
end
2023-12-04 09:00:10 +01:00
minetest.register_globalstep(function()
2023-12-04 09:23:45 +01:00
for _, player in pairs(minetest.get_connected_players()) do
local name = player:get_player_name()
if controls.players[name] then
2023-12-04 09:00:10 +01:00
update_player_controls(player, controls.players[name])
end
2023-12-04 09:23:45 +01:00
end
end)
2023-12-04 09:00:10 +01:00
if minetest.settings:get_bool("controls_enable_debug", false) then
2023-12-04 09:23:45 +01:00
dofile(minetest.get_modpath("controls") .. "/debug.lua")
2023-12-04 09:00:10 +01:00
end