#RunService.Heartbeat

1 messages · Page 1 of 1 (latest)

sage cloud
#

How do I check something important like enemies' range but with a delay that I set? I'm thinking RunService.Heartbeat:Connect(function)

but with a delay inside of it, but I think that still makes the connection every heartbeat.

#

Like for example

RunService.Heartbeat:Connect(function(dt)
        -- global players data update
        EnemyManager._checkTimer = EnemyManager._checkTimer + dt
        local heavy = false
        if EnemyManager._checkTimer >= DEFAULT_SETTINGS.checkInterval then
            EnemyManager._checkTimer = 0
            heavy = true
            -- cache player positions
            EnemyManager._playersData = {}
            for _, p in ipairs(Players:GetPlayers()) do
                local phrp = p.Character and p.Character:FindFirstChild("HumanoidRootPart")
                if phrp then table.insert(EnemyManager._playersData, { player = p, pos = phrp.Position }) end
            end
        end

        -- update enemies
        for _, enemy in ipairs(EnemyManager._enemies) do
            enemy:update(dt, EnemyManager._playersData, heavy)
        end
    end)
ionic tundra
#

player abbreviated as p 💔

#

dont do that

sage cloud
#

But I think even with the line if EnemyManager._checkTimer >= DEFAULT_SETTINGS.checkInterval then

it still makes the connection every heartbeat, just with a check for time elapsed each connection?

ionic tundra
sage cloud
ionic tundra
#

okay you really need to name your variables better

sage cloud
ionic tundra
#

and i still dont get what the code does

sage cloud
#

and if it's true is there another way to check player distance from enemies without making a connection every frame?

sage cloud
#

I don't want my code to be checking distance of every player from every enemy every single frame

ionic tundra
#

do it every 0.1 seconds

#

or less

sage cloud
#

and I think a delay line in the heartbeat connection it doesn't delay it just adds a check and there's still a connection every frame

ionic tundra
#

but you really shouldn't be making complicated optimizations before you're done implementing everything

sage cloud
sage cloud
ionic tundra
#
while true do
  task.wait(0.1)
  
  -- code
end
#

ok

sage cloud
#

I see a noticeable drop in framerate with just 30 npcs spawned in