2021-03-28 19:28:45 +05:00

105 lines
2.7 KiB
Plaintext

-- @include ../libs/constants.txt
require("../libs/constants.txt")
InputController = class("InputController")
function InputController:initialize()
self.ply = NULL_ENTITY
self.config = {} -- keys and pedal speed config
if SERVER then
self.throttle = {
target = 0,
value = 0
}
self.brake = {
target = 0,
value = 0
}
self.clutch = {
target = 0,
value = 0
}
self.start = {
target = 0,
value = 0,
type = "keyPress"
}
net.receive("input", function()
local inputName = net.readString()
local target = net.readBool()
if self[inputName] then
self[inputName].target = target and (self.config[inputName] and self.config[inputName].max or 1) or 0
end
end)
end
if CLIENT then
function setTargetInput(pressedKey, target)
local key = string.upper(input.getKeyName(pressedKey))
if self.keyToInputName[key] then
net.start("input")
net.writeString(self.keyToInputName[key].inputName)
net.writeBool(target)
net.send()
end
end
hook.add("inputPressed", "inputPress", function(key)
if (self.ply ~= NULL_ENTITY and self.ply == CURRENT_PLAYER) then
setTargetInput(key, true)
end
end)
hook.add("inputReleased", "inputRelease", function(key)
if (self.ply ~= NULL_ENTITY and self.ply == CURRENT_PLAYER) then
setTargetInput(key, false)
end
end)
net.receive("changePlayer", function()
self.ply = net.readEntity()
end)
end
end
if SERVER then
function InputController:setPlayer(ply)
self.ply = ply
net.start("changePlayer")
net.writeEntity(ply or NULL_ENTITY)
net.send()
end
function InputController:update()
for key in pairs(self.config) do
if self[key] then
local pressSpeed = self.config[key].press or 1
local releaseSpeed = self.config[key].release or 1
self[key].value = math.lerp(self[key].target == 1 and pressSpeed or releaseSpeed, self[key].value,
self[key].target)
end
end
end
end
function InputController:setConfig(config)
self.config = table.copy(config)
local keyToInputName = {}
for key, value in pairs(config) do
keyToInputName[string.upper(value.key)] = {
inputName = key
}
end
self.keyToInputName = table.copy(keyToInputName)
end