Mathias wrote:I've searched the forums for awhile, but haven't found any relating to this one:
A mod request for a speedometer, or a HUD that shows the land speed of the player, preferably in meters per second. I believe this is very approachable, but I haven't got the skills (yet) to do this. It would be really useful for other developers to test how fast, a boat, car, train, plane, or their own character is moving. As a beginner in lua, I feel it is necessary if I need to see how how long it would take for my test car to achieve maximum velocity.
This is a quick implementation:
- Code: Select all
-- Speedometer update interval, in seconds.
local INTERVAL = 1
local player_speedos = { }
local timer = 0
local function update_speedo(player)
local plname = player:get_player_name()
local speedo = player_speedos[plname]
local oldpos, hud
if speedo then
oldpos, hud = unpack(speedo)
else
oldpos = player:getpos()
hud = player:hud_add({
name = "speedo:"..plname,
hud_elem_type = "text",
text = "", -- This is updated below by `hud_change`.
number = 0xFFFF00, -- Color as 0xRRGGBB
position = { x=0, y=1 },
offset = { x=16, y=-16 }, -- In pixels
alignment = { x=1, y=-1 }, -- Bottom-left
})
speedo = { oldpos, hud }
player_speedos[plname] = speedo
end
local curpos = player:getpos()
local speed = vector.distance(curpos, oldpos) / timer
player:hud_change(hud, "text", "Speed: "..tostring(speed).." m/s")
speedo[1] = curpos
end
local function update_speedos()
for _, p in ipairs(minetest.get_connected_players()) do
update_speedo(p)
end
end
minetest.register_globalstep(function(dtime)
-- Update speedometer every INTERVAL seconds.
timer = timer + dtime
if timer >= INTERVAL then
update_speedos()
-- If you want more precise timing, use `timer = timer - INTERVAL`.
timer = 0
end
end)
minetest.register_on_leaveplayer(function(player)
-- Discard objects on player leave.
player_speedos[player:get_player_name()] = nil
end)
It's not precise in any way, but gives an approximation of the player's speed. Feel free to take it as a base and modify to your liking.
To use it, just create a directory in your `mods` directory (it can be named any way, e.g. `speedo`), and paste that code in a file named `init.lua` inside that directory (so you have `mods/speedo/init.lua`.