I’m writing a module to handle haptic inputs. I’m looking to improve the code to make it cycle though less data. I’m also looking for better practices in my code.
local hapticService = game:GetService("HapticService")
local module = {}
module.tags = {};
module.updateConnection = nil;
module.motorsToUpdate = {};
local function getClockTimeNow()
return os.clock()
end
function module.updateHapticTag(tag : string, motorIntensities : {}, lifetime : number)
if not motorIntensities then
module.tags[tag] = nil
return
end
for motor in motorIntensities do
if not table.find(module.motorsToUpdate, motor) then
table.insert(module.motorsToUpdate, motor)
end
end
module.tags[tag] = {
expiration = getClockTimeNow() + lifetime,
motorIntensities = motorIntensities,
};
end
module.updateConnection = game:GetService("RunService").Heartbeat:Connect(function()
local timeNow = getClockTimeNow()
local motorsUpdated = {}
if not module.tags then
return
end
for tag, data in module.tags do
if not data.expiration then
continue
end
if timeNow < data.expiration then
for motor, motorIntensity in data.motorIntensities do
motorsUpdated[motor] = (motorsUpdated[motor] or 0) + (motorIntensity or 0)
end
else -- tag has expired, cancel it.
module.tags[tag] = nil
end
end
for _, motor in module.motorsToUpdate do
local intensity = motorsUpdated[motor] or 0
hapticService:SetMotor(Enum.UserInputType.Gamepad1, motor, intensity)
end
end)
return module