I modified PowderNotSolid's ruler script

  • TheSuperNova
    25th Dec 2023 Member 0 Permalink

    I was experiencing some issues with PowderNotSolid's ruler script becouse it did not work if the axes were not aligned. I modified it to use the pythagorean theorem. Now it works.

     

    Here is the code.

     

    local _showing = false
    local _shift, _ctrl = false, false
    local _x, _y = 0, 0

    local function get_distance(x1, y1, x2, y2)
        local dx = x2 - x1
        local dy = y2 - y1

        local distance = math.sqrt(dx * dx + dy * dy)

        return distance
    end

    local function get_squares(x1, y1, x2, y2)
        return math.floor(get_distance(x1,y1,x2,y2)) + 1
    end

    event.register(evt.tick, function()
        local x, y = sim.adjustCoords(tpt.mousex, tpt.mousey)
       
        if _showing then
            local squares = get_squares(x, y, _x, _y)
           
            if squares > 0 then
                local straight = x == _x or y == _y

                if straight then
                    graphics.drawText(8, 60, "Dist: " .. tostring(squares) .. " (Straight)")
                else
                    graphics.drawText(8, 60, "Dist: " .. tostring(squares).. " (Not Straight)")
                end
            end
        end
    end)

    local key_trigger = function(_, _, _repeat, shift, ctrl, _)  if shift then _shift = true end if ctrl then _ctrl = true end end
    event.register(evt.keypress, key_trigger)
    event.register(evt.keyrelease, key_trigger)

    event.register(evt.mousedown, function(x, y, btn)
        _x, _y = sim.adjustCoords(x, y)
       
        if (btn == 1 or btn == 3) and ((_shift and not _ctrl) or (_ctrl and not shift)) then
            _showing = true
        end
    end)

    event.register(evt.mouseup, function(_, _, btn, _)
        if btn == 1 or btn == 3 then
            _showing = false
        end
    end)