1.创建一个坐标数组 - 这是你的路径.您可以通过多种方式实际创建数组,但结果应与以下内容类似:
var path:Array = [
Point(0, 0),
Point(20, 12),
Point(60, 72),
Point(67, 118)
];
Run Code Online (Sandbox Code Playgroud)
2.设置您的nextStep()功能或类似功能 - 这将收集有关路径中下一步的信息,例如它与当前步骤之间的角度.您还需要跟踪当前步骤,可以通过简单地存储路径数组中您所在位置的索引来表示.总而言之,它可能看起来像这样:
var currentStep:int = 0;
function nextStep():Object
{
// Object to return.
var out:Object = {
hasDestination: false,
destination: null,
radians: 0
};
var current:Point = path[currentStep];
// Check that you're not on the last step first.
if(currentStep != path.length - 1)
{
currentStep ++;
var next:Point = path[currentStep + 1];
var t:Point = next.subtract(current);
out.nextDestination = true;
out.destination = next;
out.radians = Math.atan2(t.y, t.x);
}
return out;
}
Run Code Online (Sandbox Code Playgroud)
3.使用上述信息移动 - 返回的对象nextStep()可用于改变DisplayObject您选择的位置和旋转.
假设那entity是你的DisplayObject:
var stepInfo:Object = nextStep();
if(stepInfo.hasDestination)
{
entity.rotation = stepInfo.radians * 180 / Math.PI;
entity.x = stepInfo.destination.x;
entity.y = stepInfo.destination.y;
}
else trace("End of path reached.");
Run Code Online (Sandbox Code Playgroud)
4.整理(可选) - 考虑创建自己的类nextStep()作为整洁的结果,例如:
public class StepInfo
{
public var hasDestination:Boolean = false;
public var destination:Point;
public var radians:Number = 0;
}
Run Code Online (Sandbox Code Playgroud)
我甚至建议将上述所有内容都移到Path课堂上,这样你就可以简单地做以下事情:
var path:Path = new Path();
path.generate(); // create this yourself, generates the path array.
var step:StepInfo = path.nextStep();
trace(path.currentStep);
Run Code Online (Sandbox Code Playgroud)
等等
希望这可以帮助.