Controls & Events: add controls events and refactoring code

This commit is contained in:
Van
2026-06-08 22:07:26 +03:00
parent 5146fd3e07
commit 90cf189b1a
8 changed files with 162 additions and 145 deletions

View File

@@ -0,0 +1,88 @@
---@type Events.ControlsEvents
local ControlsEvents = Smc.requireEvents('ControlsEvents')
---@class Controls
local Controls = {}
---@alias Controls.PressKey 'up'|'down'|'left'|'right'|'jump'|'aux1'|'sneak'|'dig'|'place'|'zoom'
---@alias Controls.MovementKey 'movement_x'|'movement_y'
---@alias Controls.PlayerControls table<Player.controls_key, boolean>
---@alias Controls.PlayerControlsTimer table<Player.controls_key, number>
local ControlsPressKeys = { 'up', 'down', 'left', 'right', 'jump', 'aux1', 'sneak', 'dig', 'place', 'zoom' }
local ControlsMovementKeys = { 'movement_x', 'movement_y' }
---@type table<string, Controls.PlayerControls>
local playersLastControls = {}
---@type table<string, Controls.PlayerControlsTimer>
local playersControlsTimer = {}
---@type table<string, integer>
local playersWieldIndices = {}
core.register_on_joinplayer(function(player, last_login)
local playerName = player:get_player_name()
local nowControls = player:get_player_control()
local controlsTimer = {}
for _, key in ipairs(ControlsPressKeys) do
controlsTimer[key] = 0.0
end
playersLastControls[playerName] = nowControls
playersControlsTimer[playerName] = controlsTimer
playersWieldIndices[playerName] = player:get_wield_index()
end)
core.register_on_leaveplayer(function(player, timed_out)
local playerName = player:get_player_name()
playersLastControls[playerName] = nil
playersControlsTimer[playerName] = nil
playersWieldIndices[playerName] = nil
end)
Smc.registerGlobalStepForEachPlayer(0, function(deltaTime, player)
local playerName = player:get_player_name()
local lastControls = playersLastControls[playerName]
local controlsTimer = playersControlsTimer[playerName]
local currentControls = player:get_player_control()
local lastWieldIndex = playersWieldIndices[playerName]
local currentWieldIndex = player:get_wield_index()
-- Press keys
for _, key in ipairs(ControlsPressKeys) do
local lastPressed = lastControls[key]
local currentPressed = currentControls[key]
-- on_press
if not lastPressed and currentPressed then
ControlsEvents:callOnPress(player, key)
controlsTimer[key] = 0
-- on_release
elseif lastPressed and not currentPressed then
ControlsEvents:callOnRelease(player, key, controlsTimer[key])
controlsTimer[key] = 0
-- on_hold
elseif lastPressed and currentPressed then
ControlsEvents:callOnHold(player, key, controlsTimer[key], deltaTime)
controlsTimer[key] = controlsTimer[key] + deltaTime
end
end
--TODO: add player movement callbacks
-- Wield change
if lastWieldIndex ~= currentWieldIndex then
ControlsEvents:callOnWieldChange(player, currentWieldIndex, lastWieldIndex)
end
--TODO: add mouse movement callbacks on dir
playersLastControls[playerName] = currentControls
playersControlsTimer[playerName] = controlsTimer
end)
return Controls