:NAME loot

:PARAM float32 pickup_distance

:VAR boolean have_ever_updated_before


-- ------------------- constants ------------------- 

local vectorlib = require "scripts/vector_math"

k_primary_player= e_value("e_player", "_player_primary")

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

function param_initialize(p)
	p.pickup_distance= 0.8
end

function var_initialize(v)
	v.have_ever_updated_before= false
end

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

function try_pickup(object)
	local iterator= world_state_get().component_cache.component_player.iterator_get()
	local object_point= object.world_position_get()
	local result= false

	while (true) do
		local player= iterator.next()
		if (player) then
			local player_object= player.object
			if (not player_object.is_hidden()) then
				local player_control= player_object._p.player_control
				if (player_control and player_control.can_pick_up_loot) then
					local player_point= player_object.world_position_get()
					if (vectorlib.distance2d(object_point, player_point) < param.pickup_distance) then
						result= true
					end
				end
			end
		else
			break
		end
	end
	
	return result
end


function update(object)

	if (not var.have_ever_updated_before) then
		local game_hud= world_state_get().global_script("game_hud")
		if (game_hud) then
			game_hud.loot_remaining_count = game_hud.loot_remaining_count+1
		end
		var.have_ever_updated_before= true
	end

	if (try_pickup(object)) then
		local game_hud= world_state_get().global_script("game_hud")
		if (game_hud) then
			game_hud.loot_pending_count= game_hud.loot_pending_count+1
			local sound= object.sound_get()
			if (sound) then
				sound.play_sound("aquired", false)
			end
			
			object_delete(object)
		end
	end
end

component_register(nil, update, nil, nil)
