item_names.lua 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. -- Based on 4itemnames mod by 4aiman
  2. local item_names = {} -- [player_name] = { hud, dtime, itemname }
  3. local dlimit = 3 -- HUD element will be hidden after this many seconds
  4. local air_hud_mod = minetest.get_modpath("4air")
  5. local hud_mod = minetest.get_modpath("hud")
  6. local hudbars_mod = minetest.get_modpath("hudbars")
  7. local function set_hud(player)
  8. local player_name = player:get_player_name()
  9. local off = {x=0, y=-70}
  10. if air_hud_mod or hud_mod then
  11. off.y = off.y - 20
  12. elseif hudbars_mod then
  13. off.y = off.y + 13
  14. end
  15. item_names[player_name] = {
  16. hud = player:hud_add({
  17. hud_elem_type = "text",
  18. position = {x=0.5, y=1},
  19. offset = off,
  20. alignment = {x=0, y=0},
  21. number = 0xFFFFFF,
  22. text = "",
  23. }),
  24. dtime = dlimit,
  25. index = 1,
  26. itemname = ""
  27. }
  28. end
  29. minetest.register_on_joinplayer(function(player)
  30. minetest.after(0, set_hud, player)
  31. end)
  32. minetest.register_on_leaveplayer(function(player)
  33. item_names[player:get_player_name()] = nil
  34. end)
  35. minetest.register_globalstep(function(dtime)
  36. for _, player in pairs(minetest.get_connected_players()) do
  37. local data = item_names[player:get_player_name()]
  38. if not data or not data.hud then
  39. data = {} -- Update on next step
  40. set_hud(player)
  41. end
  42. local index = player:get_wield_index()
  43. local stack = player:get_wielded_item()
  44. local itemname = stack:get_name()
  45. if data.hud and data.dtime < dlimit then
  46. data.dtime = data.dtime + dtime
  47. if data.dtime > dlimit then
  48. player:hud_change(data.hud, 'text', "")
  49. end
  50. end
  51. if data.hud and (itemname ~= data.itemname or index ~= data.index) then
  52. data.itemname = itemname
  53. data.index = index
  54. data.dtime = 0
  55. local desc = stack.get_meta
  56. and stack:get_meta():get_string("description")
  57. if not desc or desc == "" then
  58. -- Try to use default description when none is set in the meta
  59. local def = minetest.registered_items[itemname]
  60. desc = def and def.description or ""
  61. end
  62. player:hud_change(data.hud, 'text', desc)
  63. end
  64. end
  65. end)