algorithm - 如何计算二次贝塞尔曲线和水平线之间的交点?

标签 algorithm lua bezier quadratic

我想要做的是获取某个贝塞尔曲线与水平线(y 坐标)相交的 X 坐标。目前,我有这段代码:

function self.getX(y)
    if y > maxY or y < minY then
        return
    end
    local a = y1 - y
    if a == 0 then
        return
    end
    local b = 2*(y2 - y1)
    local c = (y3 - 2*y2 + y1)

    local discriminant = (b^2 - 4*a*c )

    if discriminant < 0 then
        return
    else
        local aByTwo = 2*a
        if discriminant == 0 then
            local index1 = -b/aByTwo
            if 0 < index1 and index1 < 1 then
                return (1-index1)^2*x1+2*(1-index1)*index1*x2+index1^2*x3
            end
        else
            local theSQRT = math.sqrt(discriminant)
            local index1, index2 = (-b -theSQRT)/aByTwo, (-b +theSQRT)/aByTwo
            if 0 < index1 and index1 < 1 then
                if 0 < index2 and index2 < 1 then
                    return (1-index1)^2*x1+2*(1-index1)*index1*x2+index1^2*x3, (1-index2)^2*x1+2*(1-index2)*index2*x2+index2^2*x3
                else
                    return (1-index1)^2*x1+2*(1-index1)*index1*x2+index1^2*x3
                end
            elseif 0 < index2 and index2 < 1 then
                return (1-index2)^2*x1+2*(1-index2)*index2*x2+index2^2*x3
            end
        end
    end     
end

一些规范:

  • 这是 Lua 代码。
  • local 表示变量是代码块的本地变量,因此它不会影响代码的功能。
  • y1、y2 和 y3 是 3 个点的 y 坐标。这同样适用于 x1、x2、x3。
  • y 是我正在计算的水平线的 y 坐标。
  • maxY 是 3 个 y 中最大的一个。
  • minY 是最小的。

目前这段代码给了我这个:

enter image description here

  • 有8条贝塞尔曲线
  • 绿色的是使用正常方法生成的:(1-t)^2*x1+2*(1-t)*t*x2+t^2*x3
  • 红点是控制点。
  • 白线是使用上面代码描述的方法生成的。
  • 直线就是直线,忽略它们。
  • 应该有 8 条曲线,但只渲染了 4 条。

提前致谢

创作者!

最佳答案

贝塞尔曲线有

y(t)=(1-t)^2*y1+2(1-t)*t*y2+t^2*y

扩展为

(y1-2*y2+y3)*t^2+2(y2-y1)*t+y1

你已经交换了求解二次方程a*t^2+b*t+c=0中的ac y(t)=y.

关于algorithm - 如何计算二次贝塞尔曲线和水平线之间的交点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34832626/

相关文章:

Python字典在第一个之后不添加后续键

algorithm - 重心坐标下三角点检验的数值稳定性

svg - 在 Raphael.js 中获取两点之间的子路径,而不是位置

c# - 如何将 'hermite' 曲线转换为贝塞尔曲线?

algorithm - 通过NuSMV验证Dekker的互斥算法

c++ - 在 C++ 中比较两个大型数据列表的有效算法是什么?

lua - 在 Logitech 5.4 LUA 中弃用 table.getn 之后,此代码似乎不再起作用

lua - 确定 object[1] 是否有值?

lua - 什么是弱引用?

svg - 从贝塞尔曲线重建圆