local function throw_smokebomb(item, player)
   local playerpos = player:get_pos()
   local obj = minetest.add_entity({x=playerpos.x,y=playerpos.y+1.625,z=playerpos.z}, 'items:smoke_grenade_entity')
   local dir = player:get_look_dir()
   obj:set_velocity({x=dir.x*30, y=dir.y*30, z=dir.z*30})
   obj:set_acceleration({x=dir.x*-3, y=-dir.y^8*80-10, z=dir.z*-3})
   item:take_item()
   return item
end

local function add_smoke(pos)
   minetest.add_particlespawner({
      amount = 150,
      time = 15,
      pos = {min = {x=pos.x-.5, y=pos.y, z=pos.z-.5},
            max = {x=pos.x+.5, y=pos.y+.25, z=pos.z+.5},
            bias = 0},
      minvel = {x=-.25, y=0, z=-.25},
      maxvel = {x=.25, y=.4, z=.25},
      exptime = {min = 6, max = 12},
      collisiondetection = true,
      collision_removal = false,
      texture = {name = 'items_smoke_screen_0.png',
               blend = 'alpha',
               scale_tween = {
                  {x=5,y=5},
                  {x=15,y=15}
               }},
      texpool = {
         {name = 'items_smoke_screen_0.png',
                  blend = 'alpha',
                  scale_tween = {
                     {x=5,y=5},
                     {x=15,y=15}
                  }},
         {name = 'items_smoke_screen_1.png',
                  blend = 'alpha',
                  scale_tween = {
                     {x=5,y=5},
                     {x=20,y=20}
                  }},
         {name = 'items_smoke_screen_2.png',
                  blend = 'alpha',
                  scale_tween = {
                     {x=7,y=7},
                     {x=25,y=25}
                  }},
      }
   })
end

minetest.register_craftitem('items:smoke_grenade', {
   description = 'Smoke Grenade',
   inventory_image = 'items_smoke_grenade.png',
   groups = {not_in_creative_inventory=1, stashable=1},
   on_use = throw_smokebomb
})

minetest.register_entity('items:smoke_grenade_entity', {
   textures = {'items_smoke_grenade.png'},
   physical = true,
   collisionbox = {-.1,-.1,-.1,.1,.1,.1},
   on_step = function(self, dtime, moveresult)
      if moveresult.collides then
      local vel = self.object:get_velocity()
      --if (vel.x == 0 or vel.z == 0) and vel.y == 0 then
         if vel.y == 0 then
            local pos = self.object:get_pos()
            add_smoke(pos)
            self.object:remove()
            return self
         end
      end
   end
})
