diff --git a/train.lua b/train.lua index 84edb2a45c829ae753df1292ec9f3e28b9ccd7fc..d8f670cdd906ca5dc18c3912294dd54dd97e3d24 100644 --- a/train.lua +++ b/train.lua @@ -1,6 +1,5 @@ -local last_index = 0 -local last_line = "" +local last_set_by = {} local update_formspec = function(meta) local line = meta:get_string("line") @@ -40,12 +39,56 @@ minetest.register_node("mapserver:train", { on_construct = function(pos) local meta = minetest.get_meta(pos) - last_index = last_index + 5 + local find_nearest_player = function(pos, radius) + -- adapted from https://forum.minetest.net/viewtopic.php?t=23319 + + local closest_d = radius+1 + local closest_name + + for i, obj in ipairs(minetest.get_objects_inside_radius(pos, radius)) do + -- 0.4.x compatibility: + --if obj:get_player_name() ~= "" then + + -- 5.0.0+ method: + if minetest.is_player(obj) then + local distance = vector.distance(obj:get_pos(), pos) + if distance < closest_d then + closest_d = distance + closest_name = obj:get_player_name() + end + end + end + + -- if 'closest_name' is nil, there's no player inside that radius + return closest_name + end + + -- 10 should be the max possible interaction distance + local name = find_nearest_player(pos, 10) + + local last_index = 0 + local last_line = "" + local last_color = "" + + if name ~= nil then + name = string.lower(name) + if last_set_by[name] ~= nil then + last_index = last_set_by[name].index + 5 + last_line = last_set_by[name].line + last_color = last_set_by[name].color + else + last_set_by[name] = {} + end + + last_set_by[name].index = last_index + last_set_by[name].line = last_line + last_set_by[name].color = last_color + end meta:set_string("station", "") meta:set_string("line", last_line) meta:set_int("index", last_index) - meta:set_string("color", "") + meta:set_string("color", last_color) update_formspec(meta) end, @@ -57,17 +100,27 @@ minetest.register_node("mapserver:train", { end local meta = minetest.get_meta(pos) + local name = string.lower(sender:get_player_name()) if fields.save then - last_line = fields.line - meta:set_string("color", fields.color) - meta:set_string("line", fields.line) - meta:set_string("station", fields.station) + if last_set_by[name] == nil then + last_set_by[name] = {} + end + local index = tonumber(fields.index) if index ~= nil then - last_index = index - meta:set_int("index", index) + index = index end + + meta:set_string("color", fields.color) + meta:set_string("line", fields.line) + meta:set_string("station", fields.station) + meta:set_int("index", index) + + last_set_by[name].color = fields.color + last_set_by[name].line = fields.line + last_set_by[name].station = fields.station + last_set_by[name].index = index end update_formspec(meta)