Log In  

Hey, I'm a relative beginner, and I've been trying to create a general-purpose shape collider for a little project I'm making. I've run into a bit of a problem when trying to make a function for detecting collision between circles and rectangles. The problem is, as far as I can tell, that Pico-8 doesn't have enough floating point precision to accurately calculate the distance between a point and a line (using a formula I copped off of Wikipedia). Here's what I've got:

-- I'm aware these function names are garbage, I'm gonna change them up later.
local function dOfLine(a, b)
  -- takes two points and returns the distance between
  return sqrt((b.y - a.y)^2 + (b.x - a.x)^2)
end

local function dToLine(p, a, b)
    -- takes a point and the two endpoints of a line and returns the length
    -- of the perpendicular between the point and the line.
    num = abs(((b.y - a.y) * p.x - (b.x - a.x) * p.y + b.x * a.y - b.y * a.y))
    return num / dOfLine(a, b)
end

Am I right in thinking that this is a platform limitation? When fed points (4, 7), (1, 5), (1,10) it resolves num as 25, and returns 5, which is of course incorrect.

Does anyone have any workarounds, or am I gonna have accept this limitation?

P#44863 2017-10-02 14:13 ( Edited 2017-10-02 20:37)

Squares are definitely very prone to overflow but...
in your case, the formula is incorrect (the term b.x a.y - b.y a.y is wrong) :)

Correct version:

function dist2line(r,a,b)
    local dx=b.x-a.x
    local dy=b.y-a.y
    local d=sqrt(dx*dx+dy*dy)
    return abs(dx*(a.y-r.y)-dy*(a.x-r.x))/d
end

print(dist2line(
    {x=4,y=7},
    {x=1,y=5},
    {x=1,y=10}))
-- prints 3
P#44865 2017-10-02 15:08 ( Edited 2017-10-02 19:08)

Thank you very much! This seems to work perfectly.

P#44870 2017-10-02 16:37 ( Edited 2017-10-02 20:37)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-04-19 07:14:17 | 0.007s | Q:9