Line2DMove.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. * @param start_x 起始点
  13. * @param start_y
  14. * @param end_x 终点
  15. * @param end_y
  16. * @param speed 速度
  17. * @param addSpeed 加速度
  18. * 起点终点一致时没有速度将不起作用
  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. if (dis <= 0) {
  27. this._percent = 1;
  28. this._percentSpeed = 0;
  29. this._percentAddSpeed = 0;
  30. } else {
  31. this._percent = 0;
  32. this._percentSpeed = speed / dis;
  33. this._percentAddSpeed = addSpeed / dis;
  34. }
  35. }
  36. public get target_pos_x(): number {
  37. return this._e.x;
  38. }
  39. public get target_pos_y(): number {
  40. return this._e.y;
  41. }
  42. public get current_dir(): Vec2 {
  43. return this._currentDir;
  44. }
  45. public get isEnd(): boolean {
  46. return this._percent >= 1;
  47. }
  48. public get percent(): number {
  49. return this._percent;
  50. }
  51. /**
  52. * 向目标运动
  53. * @param dt 帧时间
  54. * @param mb 目标点,没有的话为初始定义的点
  55. * @returns
  56. */
  57. public MoveTo(dt: number, mb: Vec2 = null): Vec2 {
  58. if (this._percentSpeed == 0 && this._percentAddSpeed == 0) return this._current;
  59. this._percentSpeed += this._percentAddSpeed * dt;
  60. this._percent += this._percentSpeed * dt;
  61. let nextpos = this.getPos(this._percent, this._s, mb == null ? this._e : mb);
  62. this._current.x = nextpos.x;
  63. this._current.y = nextpos.y;
  64. return this._current;
  65. }
  66. /**
  67. * 获取进度位置
  68. * @param t 当前时间进度 0-1
  69. * @param a 起点
  70. * @param b 控制点
  71. * @param c 终点
  72. */
  73. private _ab = new Vec2();
  74. private getPos(t: number, a: Vec2, b: Vec2): Vec2 {
  75. Vec2.lerp(this._ab, a, b, t);
  76. return this._ab;
  77. }
  78. }