dist() function

A Few Useful Functions:

-- Squares x.
function square(x)
    return x*x 

-- Works out the difference between two numbers.
function diff(n1, n2)
    if n2 > n1 then
        return n2 - n1
    elseif n1 > n2 then
        return n1 - n2
        return 0

-- Can be used in simulations to work out the distance (in pixels) between two points.
function dist(x1, y1, x2, y2)
    return math.sqrt(square(diff(x1, x2))+square(diff(y1, y2)))

-- Can be used to find the triangular number of x.
function tri(x)
    t = 0
    for i = 1, x do
        t = t + i 
    return t

-- Can be used to find the oblong number of x.
function ob(x)
    o = 0
    for i = 1, x do
        o = o + i*2
    return o

Above are some very useful math functions (by me), but most useful is the dist(x1, y1, x2, y2), which can calculate the distance (in pixels) between two points using Pythagorean theorem. Please let me know of any problems.

for distance, you can also use vec2 and vec3 dist, aVector:dist(anotherVector).

For your difference function, you could use math.abs to always get the positive version, then it would just be:

function diff(n1, n2)
return math.abs(n2-n1)

TBH, I’d rather just right x*x or math.abs(n2-n1) directly in my code than create a squared and diff functions

Agreed, I would check the available functions in the reference befor bothering to write your own. The built in functions will always be faster.

what do the vec2 and vec3 distance functions do, exactly?

I could explain them, but you can go to @Ignatz tutorials and read it just as easily as reading the answer here.

or look in the reference link at top, under vectors

the simple explanation is that they’re a way to bundle x and y coordinates together. ie instead of

x,y = 5,10



and then you can access individual coordinates with .x eg:

print(pos.x) --prints 5
print(pos.y) -- prints 10

The advantage of doing this is that you have access to an entire library of geometry functions.