沿线增加点数

时间:2012-04-25 14:12:21

标签: actionscript-3

我正在使用以下代码计算从A点(右上角)到B点(左下角)的增量。但随着我们越来越接近B点,我的增量越来越远离预期的路径。图中的绿线是白点的预期路径。

discrepancy

    public function get target():Point { return _target; }
    public function set target(p:Point):void
    {
        _target = p;
        var dist:Number = distanceTwoPoints(x, _target.x, y, _target.y); //find the linear distance
        //double the steps to get more accurate calculations. 2 steps are calculated each frame
        var _stepT:Number = 2 * (dist * _speed); //_speed is in frames/pixel (something like 0.2)

        if (_stepT < 1) //Make sure there's at least 1 step
            _stepT = 1;
        _stepTotal = int(_stepT); //ultimately, we cannot have half a step
        xInc = (_target.x - x) / _stepT; //calculate the xIncrement based on the number of steps (distance / time)
        yInc = (_target.y - y) / _stepT;
    }

    private function distanceTwoPoints(x1:Number, x2:Number, y1:Number, y2:Number):Number 
    {
        var dx:Number = x1-x2;
        var dy:Number = y1-y2;
        return Math.sqrt(dx * dx + dy * dy);
    }

基本上,我没有想法。唯一让白点跟随绿线的东西就是如此调整目标的位置:

distanceTwoPoints(x, _target.x + 2, y, _target.y + 1);
//...
xInc = (_target.x + 2 - x) / _stepT;
yInc = (_target.y + 1 - y) / _stepT;

然而,这会抛弃模拟中其他部分之间没有角度的部分,例如进入A点(右上角)。这让我觉得两点之间的距离需要计算得比实际更短。有什么想法吗?

1 个答案:

答案 0 :(得分:9)

Flash具有很好的功能,非常方便。 Point.interpolate(pointA, pointB, number)它返回A点和B点之间的一个点。第三个输入(Number)是结果点应该与pointA或pointB的接近程度,从0到1.你必须计算它的值。

插值的作用基本上是两个输入点的加权平均值,数字是指向一个点的权重。如果数字为0.5,您将在两个输入点之间得到一个点。 1返回PointA,0返回PointB。

flash.geom.Point.interpolate()了解详情。

对于其他语言或一般数学,您可以这样做,不需要Trig:point1,原点和point2终点。 point3point1point2之间的一个点。 locpoint1point2之间的比率,距离该行的距离有多远。从loc = .25point1point2将是四分之一。 point3.x = point1.x * (1 - loc) + point2.x * locpoint3.y = point1.y * (1 - loc) + point2.y * loc。这甚至适用于0-1之外的值,例如连接point1point2但不在它们之间的点上的点。