package vector.steering
{
public class SteeredVehicle extends Vehicle
{
private var _maxForce:Number = 1; //旋转力
private var _steeringForce:Vector2D; //作为叠加后的转向合力
public function SteeredVehicle()
{
_steeringForce = new Vector2D();
super();
}
public function set maxForce(value:Number):void{
_maxForce = value;
}
public function get maxForce():Number{
return _maxForce;
}
/**
* 主要控制旋转力
*/
override public function update():void{
_steeringForce.truncate(_maxForce);
_steeringForce = _steeringForce.divide(_mass);
_velocity = _velocity.add(_steeringForce);
_steeringForce = new Vector2D();
super.update();
}
/**
* 寻找行为 把机车移动到指定点
*/
public function seek(target:Vector2D):void{
var desiredVelocity:Vector2D = target.substract(_position);
desiredVelocity.normalize();
desiredVelocity = desiredVelocity.multiply(_maxSpeed);
var force:Vector2D = desiredVelocity.substract(_velocity);
_steeringForce = _steeringForce.add(force);
}
/**
* 避开行为
*/
public function flee(target:Vector2D):void{
var desiredVelocity: Vector2D = target.substract(_position);
desiredVelocity.normalize();
desiredVelocity = desiredVelocity.multiply(_maxSpeed);
var force: Vector2D = desiredVelocity.substract(_velocity);
_steeringForce = _steeringForce.substract(force);
}
}
}
--测试类
package vector.chapter1
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import vector.steering.SteeredVehicle;
import vector.steering.Vector2D;
import vector.steering.Vehicle;
public class FleeTest extends Sprite
{
private var _vehicle:SteeredVehicle;
public function FleeTest(){
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
_vehicle = new SteeredVehicle();
_vehicle.position = new Vector2D(200, 200);
_vehicle.edgeBehavior = Vehicle.BOUNCE;
addChild(_vehicle);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(event:Event):void
{
_vehicle.flee(new Vector2D(mouseX, mouseY));
_vehicle.update();
}
}
}
避开行为与寻找行为彻底相反。实际上,除了代码最后一行用相减代替了相加以外,其它都一样。