Files
Roblox-Elevator-Game/src/shared/Client/KeyBinds.lua
2024-02-21 13:23:23 -05:00

82 lines
2.0 KiB
Lua

--I couldn't get ContextActionService to work how i wanted it to
local BindLink = {}
BindLink.__index = BindLink
local UIS = game:GetService("UserInputService")
export type KeyBindMap = {
[string]: {
[Enum.KeyCode]: () -> ()
}
}
export type InputBegan = RBXScriptConnection
export type InputEnded = RBXScriptConnection
type CallbackFunction = () -> ()
function BindLink.constructor(gameProcessing: boolean) --Allow multiple bindings of the same keys, no overwrites
type BindConstructor = {
BindMap: KeyBindMap,
InputBegan: InputBegan,
InputEnded: InputEnded
}
local self = {} :: BindConstructor
self.BindMap = {
Began = {},
Ended = {}
}
--Return these for convenience
self.InputBegan = UIS.InputBegan:Connect(function(input, gameProcessedEvent)
if gameProcessing and gameProcessedEvent or not gameProcessedEvent then
local switch = self.BindMap.Began[input.KeyCode]
if switch then
switch()
else
--switch.default()
end
end
end)
self.InputEnded = UIS.InputEnded:Connect(function(input, gameProcessedEvent)
if gameProcessing and gameProcessedEvent or not gameProcessedEvent then
local switch = self.BindMap.Ended[input.KeyCode]
if switch then
switch()
else
--switch.default()
end
end
end)
return setmetatable(self, BindLink)
end
function BindLink:AddInputBegan(Keys: {Enum.KeyCode}, Callback: CallbackFunction)
for i = 1, #Keys do
local Key = Keys[i]
if self.BindMap.Began[Key] then
warn(`Key >began< "{Key.Name}" is already binded on this KeyBind map`, debug.traceback())
end
self.BindMap.Began[Key] = Callback
end
end
function BindLink:AddInputEnded(Keys: {Enum.KeyCode}, Callback: CallbackFunction)
for i = 1, #Keys do
local Key = Keys[i]
if self.BindMap.Ended[Key] then
warn(`Key >ended< "{Key.Name}" is already binded on this KeyBind map`, debug.traceback())
end
self.BindMap.Ended[Key] = Callback
end
end
function BindLink:KeyHold(Key: Enum.KeyCode): boolean
return UIS:IsKeyDown(Key)
end
return BindLink