Cubic bezier curve arc length is always zero

别等时光非礼了梦想. 提交于 2019-12-25 02:09:56

问题


I've written the following code to calculate the length of a cubic bezier curve. I got the idea from Calculate the arclength, curve length of a cubic bezier curve. Why is not working?. The problem is it always produces a length of zero.

public Vector2 SegmentAtPoint(int segmentIndex, float t)
{
    t = Mathf.Clamp01(t);
    float oneMinusT = 1f - t;

    return
        oneMinusT * oneMinusT * oneMinusT * points[segmentIndex * 3] + 
        3f * oneMinusT * oneMinusT * t * points[segmentIndex * 3 + 1] +
        3f * oneMinusT * t * t * points[segmentIndex * 3 + 2] +
        t * t * t * points[segmentIndex * 3 + 3];

}

public float SegmentLength(int segmentIndex)    {
    var steps = 10;
    var t = 1 / steps;
    var sumArc = 0.0f;
    var j = 0.0f;
    var a = new Vector2(0.0f, 0.0f);
    var b = points[segmentIndex * 3];

    var dX = 0.0f;
    var dY = 0.0f;
    var dS = 0.0f;

    for (int i = 0; i < steps; j = j + t)
    {
        a = SegmentAtPoint(segmentIndex, j);

        dX = a.x - b.x;
        dY = a.y - b.y;
        dS = Mathf.Sqrt((dX * dX) + (dY * dY));

        sumArc = sumArc + dS;
        b.x = a.x;
        b.y = a.y;
        i++;
    }

    return sumArc;

}

回答1:


Code var t = 1 / steps; makes integer division, so result t is zero

Also note that j = j + t is executed after every loop, so at the first iteration j==0

This flaw causes such problem: both b and a are equal at the first iteration because j still remains =0. So you calculate segment lengths on intervals: 0-0, 0-0.1, 0.1-0.2...0.7-0.8,0.8-0.9 - ignoring 0.9-1.0 interval



来源:https://stackoverflow.com/questions/55006480/cubic-bezier-curve-arc-length-is-always-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!