pinball/assets/Scripts/TweenPath.ts

48 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-03-01 03:08:57 -08:00
import { _decorator, Component, Node, Tween, tween, TweenSystem } from 'cc';
const { ccclass, property, float } = _decorator;
@ccclass('TweenPath')
export class TweenPath extends Component {
@property(Node)
private target: Node;
@property([Node])
private waypoints: Node[] = [];
@property(Node)
private startPoint: Node;
@float
private duration = 2;
private tweenPath: Tween<Node>;
protected onEnable(): void {
this.startFollow(1);
}
protected onDisable(): void {
this.stopFollow();
}
private followPath(duration: number) {
this.tweenPath = tween(this.target);
for (let i = 0; i < this.waypoints.length; i++) {
this.tweenPath.to(duration, {
position: this.waypoints[i].getPosition(),
});
}
// repeatForever method bug: not repeat on completed tween, use repeat(Number.MAX_SAFE_INTEGER, this.tweenPath) instead repeatForever to make infinite loop
this.tweenPath.repeat(Number.MAX_SAFE_INTEGER, this.tweenPath);
this.tweenPath.start();
}
public stopFollow() {
this.tweenPath?.stop();
}
public startFollow(speed: number = 1) {
if (this.waypoints.length > 0) {
this.target.setPosition(this.startPoint?.position || this.waypoints[this.waypoints.length - 1].position);
this.followPath(this.duration / speed);
}
}
}