init.lua 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. local update_interval = minetest.settings:get("player_rightclick_step") or 0.2
  2. local player_rightclick_range = minetest.settings:get("player_rightclick_range") or 4
  3. p2p = {
  4. events = {},
  5. register_on_right_clickplayer = function(func)
  6. assert(type(func) == "function", "must include a function with the following arguements (clicker, clicked).")
  7. p2p.events[#p2p.events+1] = func
  8. return
  9. end
  10. }
  11. --[Local Function] get clicked player userdata using raycast (returns userdata, if failed returns nil)
  12. --Kudos to jordach for tips relating the use of raycast
  13. local function verify_clicked_player(clicker, range)
  14. local result = nil
  15. --Raycast stuff.
  16. local ray_start = vector.add(clicker:get_pos(), {x=0, y= clicker:get_properties().eye_height, z=0})
  17. local ray_modif = vector.add(vector.multiply(clicker:get_look_dir(), range), clicker:get_eye_offset())
  18. local ray_end = vector.add(ray_start, ray_modif)
  19. local ray = minetest.raycast(ray_start, ray_end, true, false)
  20. local clicked = ray:next()
  21. --
  22. clicked = ray:next()
  23. if clicked and clicked.type == "object" and clicked.ref:is_player() and clicked.ref ~= clicker then
  24. result = clicked.ref
  25. end
  26. return result
  27. end
  28. local function handle_on_right_clickplayer()
  29. for _,clicker in pairs(minetest.get_connected_players()) do
  30. local right_click = clicker:get_player_control().RMB or false
  31. --Only execute the following if a player is right clicking
  32. if clicker and right_click == true then
  33. local name = clicker:get_player_name()
  34. local clicked = verify_clicked_player(clicker, player_rightclick_range)
  35. --Do right click event when a player was right clicked
  36. if clicked then
  37. for _,func in pairs(p2p.events) do
  38. func(clicker, clicked)
  39. end
  40. end
  41. break
  42. end
  43. end
  44. minetest.after(update_interval, function()
  45. handle_on_right_clickplayer()
  46. end)
  47. end
  48. --Activate player-to-player right clicking handler
  49. minetest.register_on_mods_loaded(function()
  50. minetest.after(update_interval, function()
  51. handle_on_right_clickplayer()
  52. end)
  53. end)