Advertisement
SneakySquid

Simple Health Regen

Jul 17th, 2024
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.59 KB | Gaming | 0 0
  1. local RegenDelay = 3
  2.  
  3. local RegenAmount = {
  4.     [10] = 15,
  5.     [25] = 12.5,
  6.     [40] = 10,
  7.     [55] = 7.5,
  8.     [70] = 5,
  9.     [85] = 2.5,
  10.     [100] = 1,
  11. }
  12.  
  13. local RegenTimers = setmetatable({}, {
  14.     __index = function(self, ply)
  15.         self[ply] = util.Timer()
  16.         return self[ply]
  17.     end
  18. })
  19.  
  20. local PreviousHealth = setmetatable({}, {
  21.     __index = function(self, ply)
  22.         self[ply] = ply:Health()
  23.         return self[ply]
  24.     end
  25. })
  26.  
  27. local GetRegenPercent do
  28.     local sorted_amounts = {} do
  29.         for k, v in pairs(RegenAmount) do
  30.             table.insert(sorted_amounts, {k / 100, v / 100})
  31.         end
  32.  
  33.         table.sort(sorted_amounts, function(a, b)
  34.             return a[1] < b[1]
  35.         end)
  36.     end
  37.  
  38.     function GetRegenPercent(health_frac)
  39.         for i, v in ipairs(sorted_amounts) do
  40.             if health_frac <= v[1] then
  41.                 return v[2]
  42.             end
  43.         end
  44.  
  45.         return 0
  46.     end
  47. end
  48.  
  49. hook.Add("PlayerTick", "Health Regen", function(ply)
  50.     local regen_timer = RegenTimers[ply]
  51.  
  52.     local health = ply:Health()
  53.     local max_health = ply:GetMaxHealth()
  54.     local health_frac = health / max_health
  55.  
  56.     if health_frac <= 0 and regen_timer:Started() then
  57.         regen_timer:Reset()
  58.     elseif health_frac < 1 then
  59.         if PreviousHealth[ply] < health then
  60.             regen_timer:Start(RegenDelay)
  61.             regen_timer.InitialDelay = true
  62.         end
  63.  
  64.         if not regen_timer:Started() then
  65.             regen_timer:Start(1 / (max_health * GetRegenPercent(health_frac)))
  66.             regen_timer.InitialDelay = false
  67.         end
  68.  
  69.         if regen_timer:Elapsed() then
  70.             regen_timer:Reset()
  71.  
  72.             if not regen_timer.InitialDelay then
  73.                 ply:SetHealth(math.min(max_health, health + 1))
  74.             end
  75.         end
  76.     end
  77.  
  78.     PreviousHealth[ply] = health
  79. end)
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement