九.路径跟随
路径跟随,就是按照指定的路径行驶,这个就简单了,看下面的讨论吧!
9.1 目的
如题,机车按照指定的路径行驶
9.2 实现
靠近路径的wayPoint,Seek下一个wayPoint
9.3 讨论
路径跟随的基本思路就是假设在路径上有n个wayPoint,这样机车的路径跟随就可以化解为seek一个一个的wayPoint,这样就不用路径中那些弧形弯而犯愁了.好了,看看程序怎么实现吧.
首先我们要向一个wayPoint进行行驶,如前面讲的使用seek方法,当机车与wayPoint的距离dist小于特定的pathThreshold时,seek下一个wayPoint(一句话把整章的内容都说出来了,太简单了,确实是没什么好讲的),直接看代码吧,更加明了:
public function followPath(path:Array, loop:Boolean = true):void {
//当前的wayPoint
var wayPoint:Vector2D = path[_pathIndex];
if (wayPoint == null) return;
//是否到达当前wayPoint
if (_position.dist(wayPoint) < _pathThreshold) {
if (_pathIndex >= path.length - 1) {
//如果是最后一个wayPoint,如果循环,返回到第一个wayPoint
if (loop) {
_pathIndex = 0;
}else {
arrive(wayPoint);
}
}else {
//如果已经到达,seek下一个wayPoint
_pathIndex++;
}
}else {
seek(wayPoint);
}
}
文档followPath类:
package
{
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import ladeng6666.steering.Vector2D;
import ladeng6666.steering.Vehicle;
import ladeng6666.steering.TargetObj;
public class followPath extends Sprite
{
private var pathVehicle:Vehicle; //机车实例
private var pathMap:Sprite;
private var wayPointList:Array;
public function followPath()
{
pathVehicle = new Vehicle();
pathVehicle.position = new Vector2D(50, 250);
pathMap = new Sprite();
wayPointList = new Array();
addChild(pathVehicle);
addChild(pathMap);
conifgEvent();
var tip:TextField = new TextField();
tip.text = "请单击添加新的wayPoint!";
tip.selectable = false;
tip.width = 200;
addChild(tip);
}
private function conifgEvent():void {
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
}
//按照帧频随速度更新机车的位置
private function enterFrameHandler(e:Event):void {
pathVehicle.followPath(wayPointList);
pathVehicle.update();
}
private function mouseDownHandler(e:MouseEvent):void {
if (wayPointList.length == 0) {
pathMap.graphics.lineStyle(1);
pathMap.graphics.moveTo(mouseX, mouseY);
}
var wayPoint:Vector2D = new Vector2D(mouseX, mouseY);
var targetObj:TargetObj = new TargetObj();
targetObj.position = wayPoint;
wayPointList.push(wayPoint);
addChild(targetObj);
pathMap.graphics.lineTo(mouseX, mouseY);
}
}
}
本章源代码:
chapter9.rar (53.3 KB)