好的,你需要做两件事:
从多个片段创建一个循环的 3D 三次贝塞尔曲线
创建一个自定义补间函数,它将您的对象作为目标,将贝塞尔循环作为路径和总循环时间。
三次贝塞尔曲线的一个片段总是需要 4 个顶点,一个完整的循环必须包含至少 2 个线段,因此您需要随机创建至少 7 个顶点。顶点的数量始终是3 * NumberOfSegments + 1
,但我们将存储3 * NumberOfSegments
第一个顶点等于最后一个顶点
最简单的情况(2段,6个顶点):
...
private function generateRandomPoints():Vector<Vector3D>
{
var resultingVector:Vector<Vector3D> = new Vector<Vector3D>();
for(var i:int = 0; i < 6; i++)
{
var x:Number = Math.random() * 10;
var y:Number = Math.random() * 10;
var z:Number = Math.random() * 10;
var currentPoint3D:Vector3D = new Vector3D(x, y, z);
resultingVector.push(currentPoint3D);
}
return resultingVector;
}
...
现在,当我们有了路径时,我们可以解析它以获得这种补间效果。您可以在每次需要新坐标时调用此函数(但您需要将初始时间存储在某处),或者创建一个 tweener 对象来为您处理所有事情。我将展示最基本的示例 - 自治功能:
public static function getNextCoordinates(loopStartTime:int, totalLoopTime:int, path:Vector.<Vector3D>):Vector3D
{
var resultingPoint:Vector3D = new Vector3D();
var passedTime:int = getTimer() - loopStartTime;
//Total passed ratio
var passedRatio:Number = passedTime / totalLoopTime;
var totalSegments:int = path.length / 3;
var totalTimePerSegment:Number = totalLoopTime / totalSegments;
//So it can loop forever
while (passedRatio > 1)
{
passedRatio -= 1;
}
//Let's find our current bezier curve segment number
var currentSegment:int = Math.floor( passedRatio * totalSegments);
var currentSegmentRatio:Number = (passedTime - currentSegment * totalTimePerSegment) / totalTimePerSegment;
//It can be optimized here
while (currentSegmentRatio > 1)
{
currentSegmentRatio -= 1;
}
var startingIndex:int = currentSegment * 3;
//our four path vertices
var point0:Vector3D = path[startingIndex];
var point1:Vector3D = path[startingIndex + 1];
var point2:Vector3D = path[startingIndex + 2];
//if it's a last segment, we need to "connect" to the first vertex
if (startingIndex + 3 >= path.length)
{
var point3:Vector3D = path[0];
}
else
{
point3 = path[startingIndex + 3];
}
//At last, we find our coordinates
var tempRatio:Number = 1 - currentSegmentRatio;
resultingPoint.x = tempRatio * tempRatio * tempRatio * point0.x + 3 * tempRatio * tempRatio * currentSegmentRatio * point1.x + 3 * tempRatio * currentSegmentRatio * currentSegmentRatio * point2.x + currentSegmentRatio * currentSegmentRatio * currentSegmentRatio * point3.x;
resultingPoint.y = tempRatio * tempRatio * tempRatio * point0.y + 3 * tempRatio * tempRatio * currentSegmentRatio * point1.y + 3 * tempRatio * currentSegmentRatio * currentSegmentRatio * point2.y + currentSegmentRatio * currentSegmentRatio * currentSegmentRatio * point3.y;
resultingPoint.z = tempRatio * tempRatio * tempRatio * point0.z + 3 * tempRatio * tempRatio * currentSegmentRatio * point1.z + 3 * tempRatio * currentSegmentRatio * currentSegmentRatio * point2.z + currentSegmentRatio * currentSegmentRatio * currentSegmentRatio * point3.z;
return resultingPoint;
}
您可以将此函数扩展为补间对象的一部分。我已经在 2D 空间中对其进行了测试,它完美地将精灵的运动沿着随机的多段贝塞尔曲线循环
干杯!