Line2DMove.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { Vec2 } from "cc";
  2. //直线移动
  3. export class Line2DMove {
  4. private _s:Vec2;//起始点
  5. private _e:Vec2;//终点
  6. private _percentSpeed:number;
  7. private _percentAddSpeed:number;
  8. private _percent:number;//进度
  9. private _current:Vec2;
  10. private _currentDir:Vec2;
  11. /**
  12. *
  13. * @param start_x 起始点
  14. * @param start_y
  15. * @param end_x 终点
  16. * @param end_y
  17. * @param speed 速度
  18. * @param addSpeed 加速度
  19. */
  20. constructor(start_x:number,start_y:number,end_x:number,end_y:number,speed:number,addSpeed:number){
  21. this._s = new Vec2(start_x,start_y);
  22. this._e = new Vec2(end_x,end_y);
  23. this._current= new Vec2(start_x,start_y);
  24. this._currentDir=new Vec2(this._e.x-this._s.x,this._e.y-this._s.y).normalize();
  25. let dis = (new Vec2(end_x,end_y).subtract2f(start_x,start_y)).length();
  26. this._percent=0;
  27. this._percentSpeed= speed/dis;
  28. this._percentAddSpeed = addSpeed/dis;
  29. }
  30. public get target_pos_x():number{
  31. return this._e.x;
  32. }
  33. public get target_pos_y():number{
  34. return this._e.y;
  35. }
  36. public get current_dir():Vec2{
  37. return this._currentDir;
  38. }
  39. public get isEnd():boolean{
  40. return this._percent>=1;
  41. }
  42. /**
  43. * 向目标运动
  44. * @param dt 帧时间
  45. * @param mb 目标点,没有的话为初始定义的点
  46. * @returns
  47. */
  48. public MoveTo(dt:number,mb:Vec2=null):Vec2{
  49. this._percentSpeed+=this._percentAddSpeed*dt;
  50. this._percent+=this._percentSpeed*dt;
  51. let nextpos = this.getPos(this._percent,this._s,mb==null ? this._e:mb);
  52. this._current.x=nextpos.x;
  53. this._current.y=nextpos.y;
  54. return this._current;
  55. }
  56. /**
  57. * 获取进度位置
  58. * @param t 当前时间进度 0-1
  59. * @param a 起点
  60. * @param b 控制点
  61. * @param c 终点
  62. */
  63. private _ab = new Vec2();
  64. private getPos(t:number,a:Vec2,b:Vec2):Vec2{
  65. Vec2.lerp(this._ab,a,b,t);
  66. return this._ab;
  67. }
  68. }