diff --git a/pico8lib/math.lua b/pico8lib/math.lua index 0c8b255..e23666f 100644 --- a/pico8lib/math.lua +++ b/pico8lib/math.lua @@ -85,17 +85,6 @@ end -- partially thanks to https://www.lexaloffle.com/bbs/?pid=119363 ---- Distance to a point --- Uses `dist_naive` for small values, `dist_trig` for large --- tokens: 46 --- @tparam number x X coordinate of the point --- @tparam number y Y coordinate of the point --- @treturn number Distance from 0,0 to x,y -local function dist(x,y) - if (abs(x) < 128 and abs(y) < 128) return dist_naive(x,y) - return dist_trig(x,y) -end - --- Distance to a point -- Naive distance calculation -- Overflows for dist^2>=32768 @@ -121,6 +110,17 @@ local function dist_trig(x,y) return x*cos(a)+y*sin(a) end +--- Distance to a point +-- Uses `dist_naive` for small values, `dist_trig` for large +-- tokens: 46 +-- @tparam number x X coordinate of the point +-- @tparam number y Y coordinate of the point +-- @treturn number Distance from 0,0 to x,y +local function dist(x,y) + if (abs(x) < 128 and abs(y) < 128) return dist_naive(x,y) + return dist_trig(x,y) +end + --- Distance squared to a point -- @tparam number x X coordinate of the point -- @tparam number y Y coordinate of the point diff --git a/tests/test_math.p8 b/tests/test_math.p8 index c3c51d4..1a54cfc 100644 --- a/tests/test_math.p8 +++ b/tests/test_math.p8 @@ -117,6 +117,19 @@ suite:add_test_case(Nthroot) -- Distancefunctions local Distance = TestCase("distance") +function Distance:test_dist_exact () + for _,v in ipairs({ + {0,0,0}, + {1,1,sqrt(2)}, + {3,4,5}, + {44,117,125}, + }) + do + self:assert_equal(dist(v[1],v[2]), v[3]) + self:assert_equal(dist(v[2],v[1]), v[3]) + end +end + function Distance:test_dist_naive_exact () for _,v in ipairs({ {0,0,0},