Simple healthkit giving to much hp


AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

util.PrecacheSound( "items/smallmedkit1.wav" )

function ENT:SpawnFunction( ply, tr )

	if ( !tr.Hit ) then return end
	local SpawnPos = tr.HitPos + tr.HitNormal * 8
	local ent = ents.Create( "sent_healthkit" )
	ent:SetPos( SpawnPos )
	return ent

function ENT:Initialize()
	self:SetModel( "models/items/healthkit.mdl" )
	self:PhysicsInit( SOLID_VPHYSICS )
	self:SetMoveType( MOVETYPE_VPHYSICS )
	self:SetSolid( SOLID_VPHYSICS )
	self:SetCollisionGroup( COLLISION_GROUP_WEAPON )
	self:SetTrigger( true )
    local phys = self:GetPhysicsObject()
	if (phys:IsValid()) then
function ENT:Use( activator, caller )
function ENT:Think()

function ENT:Touch( hitent )
	local Touched = 0
	if( hitent:IsPlayer() and hitent:Health() < 100 and Touched == 0 ) then
		Touched = 1
		hitent:SetHealth( math.Clamp( hitent:Health() + 25, 1, 100 ) )
		self:EmitSound( "items/smallmedkit1.wav", 100, 100 )

When I walk over it, it will randomly give me either the correct amount of health or it will double, triple, or just fill me up all the way, i have tried to counter this with the Touched Variable, but that did nothing.

Also, if you see me doing anything the wrong or out dated way or there is a better, more optimized way to do it, please, let me know.

It’s a local variable, it won’t exist after the function ends. Define self.touched = false in the entity’s initialization hook and the rest should be straightforward.

hitent:SetHealth( hitent:Health() + 25)

Because you only have an upper limit, it’s better to use math.min:
[lua]hitent:SetHealth( math.min( hitent:Health() + 25, 100 ) )[/lua]

[del]But wouldn’t that just allow it to double and triple until it’s 100?

and nope, tried that but when I do hurtme 75 in console and walk about it, my health becomes 75.

Even if I do hurtme 50, it still gives me 75 hp.[/del]

I seem to have fixed it using the self.touched method grovewinter mentioned and using math.max().

[del]New problem, it works by adding the right amount but it will go over 100 if say I had 99 hp and got a healthkit ( 25 ), my new health will be 124.[/del]

Ha, I’m proud of myself that I came up with this:
[lua]hitent:SetHealth( math.max( hitent:Health() + math.Clamp( 100 - hitent:Health(), 1, 25 ), 25 ) )[/lua]

That stops the going over 100.