123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- import { Vec2 } from "cc";
- //直线移动
- export class Line2DMove {
- private _s: Vec2;//起始点
- private _e: Vec2;//终点
- private _percentSpeed: number;
- private _percentAddSpeed: number;
- private _percent: number;//进度
- private _current: Vec2;
- private _currentDir: Vec2;
- /**
- * @param start_x 起始点
- * @param start_y
- * @param end_x 终点
- * @param end_y
- * @param speed 速度
- * @param addSpeed 加速度
- * 起点终点一致时没有速度将不起作用
- */
- constructor(start_x: number, start_y: number, end_x: number, end_y: number, speed: number, addSpeed: number) {
- this._s = new Vec2(start_x, start_y);
- this._e = new Vec2(end_x, end_y);
- this._current = new Vec2(start_x, start_y);
- this._currentDir = new Vec2(this._e.x - this._s.x, this._e.y - this._s.y).normalize();
- let dis = (new Vec2(end_x, end_y).subtract2f(start_x, start_y)).length();
- if (dis <= 0) {
- this._percent = 1;
- this._percentSpeed = 0;
- this._percentAddSpeed = 0;
- } else {
- this._percent = 0;
- this._percentSpeed = speed / dis;
- this._percentAddSpeed = addSpeed / dis;
- }
- }
- public get target_pos_x(): number {
- return this._e.x;
- }
- public get target_pos_y(): number {
- return this._e.y;
- }
- public get current_dir(): Vec2 {
- return this._currentDir;
- }
- public get isEnd(): boolean {
- return this._percent >= 1;
- }
- public get percent(): number {
- return this._percent;
- }
- /**
- * 向目标运动
- * @param dt 帧时间
- * @param mb 目标点,没有的话为初始定义的点
- * @returns
- */
- public MoveTo(dt: number, mb: Vec2 = null): Vec2 {
- if (this._percentSpeed == 0 && this._percentAddSpeed == 0) return this._current;
- this._percentSpeed += this._percentAddSpeed * dt;
- this._percent += this._percentSpeed * dt;
- let nextpos = this.getPos(this._percent, this._s, mb == null ? this._e : mb);
- this._current.x = nextpos.x;
- this._current.y = nextpos.y;
- return this._current;
- }
- /**
- * 获取进度位置
- * @param t 当前时间进度 0-1
- * @param a 起点
- * @param b 控制点
- * @param c 终点
- */
- private _ab = new Vec2();
- private getPos(t: number, a: Vec2, b: Vec2): Vec2 {
- Vec2.lerp(this._ab, a, b, t);
- return this._ab;
- }
- }
|