:NAME vitality

:PARAM float32		max_vitality

:VAR boolean		dead
:VAR boolean		invincible
:VAR float32		vitality
:VAR float32		damage
:VAR float32		scripted_damage
:VAR float32		last_damage_time

-- ------------------- initialization ------------------- 

function param_initialize(p)
	p.max_vitality= 100
end

function var_initialize(v)
	v.dead= false
	v.vitality= 0
	v.damage= 0
	v.scripted_damage= 0
	v.last_damage_time= -1
	v.invincible= false
end


-- ------------------- component ------------------- 

function attach(object)
	var.vitality= param.max_vitality
end

function update(object)

	if (var.dead) then
		var.damage= 0
	else
		if (var.damage>0) then
			if (not var.invincible) then
				var.vitality = var.vitality - var.damage
				var.last_damage_time= world_state_get().time.time
				if (var.vitality <= 0) then
					var.vitality= 0
					var.dead= true
				end
			end
			var.damage= 0
		end

		-- we take "scripted" damage even if we are invincible
		if (var.scripted_damage>0) then
			var.vitality = var.vitality - var.scripted_damage
			var.last_damage_time= world_state_get().time.time
			var.scripted_damage= 0
			if (var.vitality <= 0) then
				var.vitality= 0
				var.dead= true
			end
		end		
	end
end


component_register(attach, update, nil, nil)
