I'm trying to make a health charger SENT. You press your use button in front of it and it increments your health. My trouble is that when I use the SENT the loop runs so quickly that my health instantly jumps to maximum.
My code so far:
[code]
function ENT:Use( activator, caller )
if (activator:IsPlayer()) then
local health = activator:Health()
while health < 200 do
health = health + 1
activator:SetHealth( health )
end
end
end
[/code]
How should I go about changing the code to more slowly increment the player's health?
[code]
health = health + 0.1
[/code]
Try that.
That's because loops act instantly -- there's no conception of time in there.
What you want is a timer.
[lua]timer.Create( self:EntIndex() .. "AddHealth", 0.5, 100, function()
activator:SetHealth( activator:Health() + 1 )
end)[/lua]
[b][url=http://wiki.garrysmod.com/?title=Timer.Create]Timer.Create [img]http://wiki.garrysmod.com/favicon.ico[/img][/url][/b]
Do what Entoros said, I thought he only wanted a instant loop, but it to go up slower.
Multiply 1 with the frame delta time
PS i may just be missing out on something way easier
[editline]07:57PM[/editline]
PS frame delta time is the time betwheen frames witch is 1/fps or the time between each tick
EDIT
Do wat entoros said
PSS Luascript that will result in the speed that you gain health with will be changing with changing of the fps
The timer worked well. The medstation heals the player for up to 200 damage and it does so at the correct rate. Now I have a new problem:
If I press the use key at the medstation, it will continue to heal the player after the player releases the key. If I hold down the key at the station, healing stops until I release the key or move out of range.
Basically, I want this to work like the medstations in hl/hl2; you hold down the button and it charges your health, but only while the button is held down.
Relevant code so far:
[code]
function ENT:Use( activator, caller )
if ( activator:IsPlayer() ) then
if activator:Health() < 200 then
amountToHeal = 200 - activator:Health()
timer.Create( self:EntIndex() .. "AddHealth", 0.125, amountToHeal, function()
activator:SetHealth( activator:Health() + 1 )
end)
end
end
end
[/code]
[lua]
function ENT:Initialize()
self:SetUseType( CONTINUOUS_USE ) -- It's the default value, but just to be sure
end
local USE_FREQ = 0.125 -- How often player is healed
local MAX_HP = 200 -- Player's max HP
local HP_TICK = 1 -- How much HP to add
local lastUse, curTime = 0, 0
function ENT:Use( activator, caller )
curTime = CurTime()
if curTime - lastUse > USE_FREQ then
if activator:IsPlayer() and activator:Health() < MAX_HP then
activator:SetHealth( activator:Health() + HP_TICK )
lastUse = curTime
end
end
end
[/lua]
Perfect. Thanks for the help guys.
Sorry, you need to Log In to post a reply to this thread.