Page 1 of 1

Pick up items [solved]

PostPosted: Sat Jul 28, 2012 13:42
by PilzAdam
I want to write a function that items that are droped can be picked up by the player just by walking over them. Heres my code:
Your phone or window isn't wide enough to display the code box. If it's a phone, try rotating it to landscape mode.
Code: Select all
local players = {}

minetest.register_on_joinplayer(function(player)
    table.insert(players, player)
end)

minetest.register_on_leaveplayer(function(player)
    table.remove(players, player)
end)

minetest.register_globalstep(function(dtime)
    for i,player in ipairs(players) do
        local items = minetest.env:get_objects_inside_radius(player:getpos(),1)
        for j,item in ipairs(items) do
            if not item:is_player() and item:get_luaentity().itemstring ~= nil then
                player:get_inventory():add_item("main", ItemStack(item:get_luaentity().itemstring))
                item:remove()
            end
        end
    end
end)

The problem is that everytime I walk over one item in the inventory appears a random number (>1) of the item.
Has anybody an idea how to change the code that only one item appears in the inventory?

PostPosted: Sat Jul 28, 2012 14:00
by LolManKuba
I'm pretty sure this has already been done.

PostPosted: Sat Jul 28, 2012 14:22
by PilzAdam
LolManKuba wrote:I'm pretty sure this has already been done.

Yes but for this you have to change builtin/item.lua and builtin/item_entity.lua and I want to do this in a mod.

PostPosted: Sat Jul 28, 2012 18:44
by PilzAdam
I solved it. I think the problem was that the items werent deletet fast enough. So I changed the itemstring variable to nil so that they cant be added again.
Your phone or window isn't wide enough to display the code box. If it's a phone, try rotating it to landscape mode.
Code: Select all
minetest.register_globalstep(function(dtime)
    for i,player in ipairs(players) do
        local items = minetest.env:get_objects_inside_radius(player:getpos(),1)
        for j,item in ipairs(items) do
            if not item:is_player() and item:get_luaentity().itemstring ~= nil then
                player:get_inventory():add_item("main", ItemStack(item:get_luaentity().itemstring))
                item:remove()
                item:get_luaentity().itemstring = nil <---------------------------
            end
        end
    end
end)