【问题标题】:Intersection or overlap of two line segments两条线段相交或重叠
【发布时间】:2017-08-03 08:20:17
【问题描述】:

给定两条线段,每条线段由两个点定义,我怎样才能最有效地确定它们的交点或重叠?

交叉点被定义为实际接触的两条线段相互交叉。 重叠被定义为在每个端点具有相同的 x 值或相同的 y 值,但至少一个端点位于另一条线的点之间。

我问这个是因为我有兴趣找到一个计算两者并将交点作为线段返回的例程,即使它的两个点都在同一位置(交点而不是重叠)。

使用 Lua,计算重叠的函数是:

local function getParallelLineOverlap( ax, ay, bx, by, cx, cy, dx, dy )
    local function sortAB( a, b )
        return math.min( a, b ), math.max( a, b )
    end

    ax, bx = sortAB( ax, bx )
    cx, dx = sortAB( cx, dx )

    local OverlapInterval = nil
    if (bx - cx >= 0 and dx - ax >=0 ) then
        OverlapInterval = { math.max(ax, cx), math.min(bx, dx) }
    end

    return OverlapInterval
end

同样使用 Lua,计算交集的函数是:

local function doLinesIntersect( a, b, c, d )
    -- parameter conversion
    local L1 = {X1=a.x,Y1=a.y,X2=b.x,Y2=b.y}
    local L2 = {X1=c.x,Y1=c.y,X2=d.x,Y2=d.y}

    -- Denominator for ua and ub are the same, so store this calculation
    local _d = (L2.Y2 - L2.Y1) * (L1.X2 - L1.X1) - (L2.X2 - L2.X1) * (L1.Y2 - L1.Y1)

    -- Make sure there is not a division by zero - this also indicates that the lines are parallel.
    -- If n_a and n_b were both equal to zero the lines would be on top of each
    -- other (coincidental).  This check is not done because it is not
    -- necessary for this implementation (the parallel check accounts for this).
    if (_d == 0) then
        return false
    end

    -- n_a and n_b are calculated as seperate values for readability
    local n_a = (L2.X2 - L2.X1) * (L1.Y1 - L2.Y1) - (L2.Y2 - L2.Y1) * (L1.X1 - L2.X1)
    local n_b = (L1.X2 - L1.X1) * (L1.Y1 - L2.Y1) - (L1.Y2 - L1.Y1) * (L1.X1 - L2.X1)

    -- Calculate the intermediate fractional point that the lines potentially intersect.
    local ua = n_a / _d
    local ub = n_b / _d

    -- The fractional point will be between 0 and 1 inclusive if the lines
    -- intersect.  If the fractional calculation is larger than 1 or smaller
    -- than 0 the lines would need to be longer to intersect.
    if (ua >= 0 and ua <= 1 and ub >= 0 and ub <= 1) then
        local x = L1.X1 + (ua * (L1.X2 - L1.X1))
        local y = L1.Y1 + (ua * (L1.Y2 - L1.Y1))
        return {x=x, y=y}
    end

    return false
end

【问题讨论】:

标签: math graphics lua 2d coronasdk


【解决方案1】:

这是我的解决方案:

function get_intersection (ax, ay, bx, by, cx, cy, dx, dy) -- start end start end
    local d = (ax-bx)*(cy-dy)-(ay-by)*(cx-dx)
    if d == 0 then return end  -- they are parallel
    local a, b = ax*by-ay*bx, cx*dy-cy*dx
    local x = (a*(cx-dx) - b*(ax-bx))/d
    local y = (a*(cy-dy) - b*(ay-by))/d
    if x <= math.max(ax, bx) and x >= math.min(ax, bx) and
        x <= math.max(cx, dx) and x >= math.min(cx, dx) then
        -- between start and end of both lines
        return {x=x, y=y}
    end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    相关资源
    最近更新 更多