How would I be able to use RunService.Heartbeat to make a power system?

I wan’t to make a power system that has a value of 100 and decreases by 1 every 9 seconds. But I wan’t the decreasing time to be divided by 2 when for example a light has opened or when a door was activated. But I wan’t it to be divided even more when both a light or door opened.

I tried using a “for count” which worked but when I opened a door or a light, I had to wait for the current count to decrease before updating and dividing the 9 seconds. I did some research and I found out that RunService.Heartbeat is better for my situation. The issue is that I don’t know how to use it, and I didn’t find any tutorial with someone that had a similar problem with me. So how can I use it?

RunService.Heartbeat is an event that fires every frame that your game is running. It connects to a function that takes in the delta time (time between each frame) as the first parameter. Something like this should work:

local value = 100
local lightIsOn = true
local doorIsClosed = true

local function decreasePower(deltaT)
  --v = d/t (decreases by 1 every 9 seconds) = 1/9
  --d = vt (decrease by vt every frame) = (1/9) * (deltaT)
  local decrementAmount = 1/9 * deltaT
  --increase the rate of decrease by 2 for each door or light
  if (lightIsOn) then
    decrementAmount *= 2
  end

  if (doorIsClosed) then
    decrementAmount *= 2
  end
  --if both are open, it is going 4 times faster since it's being multiplied by 2*2

  value -= decrementAmount
end

local runService = game:GetService("RunService")
runService.Heartbeat:Connect(decreasePower)

Feel free to ask me if anything is confusing. v = d/t is a pretty famous equation, stating that the rate of change of something is equal to how much it’s changed in a certain amount of time.

1 Like

Thank you so much!! I’ve been working for days trying to find out ways so I can make this work the way I wan’t. Plus you really helped me understand how Heartbeat works. I didn’t have any idea to what delta time was and you explained it very well. Have a great day man.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.