| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- import { Vec2 } from "cc";
- //跟随移动
- export class Follow2DMove {
- private _pos:Vec2;//起始点
- private _dir:Vec2;//起始方向
- private _rot:number=0;
- private _speed:number;//移动速度
- private _speed_add:number;//移动加速度
- private _ro_speed:number;//转向速度
- private _ro_speed_add:number;//转向加速度
- /***
- *
- */
- constructor(pos:Vec2,dir:Vec2|number,speed:number=410,speed_add:number=200,ro_speed:number=60,ro_speed_add:number=150){
- this._pos = new Vec2(pos.x,pos.y);
- if(typeof(dir)=='number'){
- this.setRot(dir);
- }else{
- this.setRotByDir(dir);
- }
- this._speed =speed;
- this._speed_add= speed_add;
- this._ro_speed = ro_speed;
- this._ro_speed_add = ro_speed_add;
- //
- }
- public get pos():Vec2{
- return this._pos;
- }
- public get dir():Vec2{
- return this._dir;
- }
- public get rot():number{
- return this._rot;
- }
- public setRotByDir(dir:Vec2){
- this._dir = dir.clone();
- this._rot = this.DirToRot(this._dir);
- }
- public setRot(an:number){
- this._rot = an;
- this._dir = this.RotToDir(this._rot);
- }
- private readonly _dr:number= 180/Math.PI;
- private readonly _rd:number = Math.PI / 180;
- private DirToRot(dir:Vec2):number{
- let radian = dir.signAngle(new Vec2(1,0));
- let angle =-this._dr* radian;
- return(angle);
- }
- private RotToDir(angle:number):Vec2{
- let radian = this._rd *angle;
- let cos = Math.cos(radian);
- let sin = Math.sin(radian);
- return new Vec2(cos, sin).normalize();
- }
- //
- /**本坐标到一个点的方向*/
- private GetDirXY(x:number,y:number):Vec2{
- return new Vec2(x-this._pos.x,y-this._pos.y).normalize();
- }
- private RotationDir(dir:Vec2,angle:number):Vec2
- {
- let radian = Math.PI / 180 *angle;
- let sin = Math.sin(radian);
- var cos = Math.cos(radian);
- var newX = dir.x * cos + dir.y * sin;
- var newY = dir.x * -sin + dir.y * cos;
- dir.x=newX;
- dir.y=newY;
- return dir;
- }
- /**追踪目标x,y*/
- public FollowXY(x:number,y:number,dt:number):void
- {
- let mbdir = this.GetDirXY(x,y);//目标方向
- let vdir = this._dir;//当前方向
- let jd = 180 / Math.PI * vdir.signAngle(mbdir);
- this._ro_speed += this._ro_speed_add*dt;
- let ro = this._ro_speed*dt;
- const jdabs= Math.abs(jd);
- if(ro>=jdabs){
- ro = jd>0 ? -jdabs:jdabs;
- }else{
- ro = jd>0 ? -ro:ro;
- }
- if(ro!=0)this.RotationDir(vdir,ro);
- this.setRotByDir(vdir);
- this.Move(dt);
- }
- private _fame_speed:number=0;
- public get fame_speed():number{
- return this._fame_speed;
- }
- /**向前移动不追踪*/
- public Move(dt:number):void{
- this._speed+=this._speed_add*dt;
- this._fame_speed=this._speed*dt;
- let v = this._dir.clone().multiplyScalar(this._fame_speed);
- this._pos.x+=v.x;
- this._pos.y+=v.y;
- }
- /**向前移动距离*/
- public MoveDis(dis:number):void{
- let v = this._dir.clone().multiplyScalar(dis);
- this._pos.x+=v.x;
- this._pos.y+=v.y;
- }
- }
|