--------------------------------------------------------------------------- -- Speedometer example mod --------------------------------------------------------------------------- function init() -- Visibility of speedometer visible = 0 -- Actual current speed currentKmh = 0 -- Displayed speed (smoothly animated) displayKmh = 0 end function tick() local v = GetPlayerVehicle() if v ~= 0 then --Show speedometer if in vehicle if visible == 0 then --Animate visibible to 1 over 0.5 seconds SetValue("visible", 1, "easeout", 0.5) end --Retrieve speed along forward direction (negative z axis) in local vehicle body transform local b = GetVehicleBody(v) local t = GetVehicleTransform(v) local vel = TransformToLocalVec(t, GetBodyVelocity(b)) local speed = -vel[3] --Speed is in meter per second, convert to km/h currentKmh = speed * 3.6 else --Hide speedometer if not in vehicle if visible == 1 then --Animate visibible to 0 over 0.5 seconds SetValue("visible", 0, "easein", 0.5) end currentKmh = 0 end end function update() --Smoothly animate the speed and clamp it between 0 and 300 --Doing this in update means it will be done independent of frame rate displayKmh = 0.95*displayKmh + 0.05*currentKmh if displayKmh < 0 then displayKmh = 0 end if displayKmh > 240 then displayKmh = 240 end end function draw() --Only draw speedometer if visible if visible > 0 then --Place it in upper right corner UiTranslate(UiWidth()+200 - 400*visible, 200) UiAlign("center middle") if GetBool("savegame.mod.mph") then UiImage("mph.png") --Convert to rotation for mph UiRotate(-displayKmh*2/1.609) else UiImage("kmh.png") --Convert to rotation for kmh UiRotate(-displayKmh) end UiImage("needle.png") end end